You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ktor后端+KMP Wasm前端:请求未带Cookie致401错误

KMP Wasm客户端请求未携带登录Cookie导致401错误

我基于Ktor后端服务器与KMP Wasm实现了一个包含Google登录功能的项目,Google登录已成功完成,认证后的会话信息已保存为Cookie,可在浏览器开发者工具中查看。但KMP Wasm客户端向后端发送API请求时,未携带该Cookie信息,导致服务器返回401无效会话错误。后端运行在localhost:8080,前端运行在同一机器的localhost:8081。参考GPT、Gemini的方案配置后问题仍未解决,相关代码如下:

服务器端CORS配置

internal fun Application.configureSession() {
    install(Sessions) {
        cookie<UserSession>("USER_SESSION") {
            cookie.extensions["SameSite"] = "None"
            cookie.secure = true
        }
    }
    install(CORS) {
        allowCredentials = true
        allowSameOrigin = true

        anyHost()
        anyMethod()
        allowHeader(HttpHeaders.ContentType)
        allowHeader(HttpHeaders.Authorization)
        allowHeader(HttpHeaders.AccessControlAllowOrigin)
    }
}

客户端配置

actual val client: HttpClient = HttpClient(Js) {
    engine {

    }
    install(DefaultRequest) {
        headers {
            append(HttpHeaders.ContentType, ContentType.Application.Json)
        }
    }
    install(ContentNegotiation) {
        json(json = Json {
            isLenient = true
            ignoreUnknownKeys = true
        })
    }
    install(Logging)
    install(HttpCookies)
}

服务器端Google OAuth处理代码

authenticate(GOOGLE_AUTH) {
    get("/login") { }

    get("/callback") {
        val tokenResponse = call.principal<OAuthAccessTokenResponse.OAuth2>()
        if (tokenResponse == null) {
            call.respondRedirect("/")
            return@get
        }

        val state = tokenResponse.state
        if (state.isNullOrBlank()) {
            call.respondRedirect("/")
            return@get
        }

        val token = tokenResponse.accessToken
        val me = signInService.signIn(token)

        call.sessions.set(UserSession(me.id)) // 会话已保存,可在浏览器开发者工具中查看
        println("[test] callback - session is saved: $me")
        call.respondRedirect("/")
    }
}

内容的提问来源于stack exchange,提问作者dev.farmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:26:00