Ktor后端+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
相关产品推荐
相关产品推荐

