如何配置HTTP客户端存储和发送cookies?

问题描述 投票:0回答:0

我正在使用 HTTP 客户端使用来自后端的服务。默认配置不保留服务器发送的 cookie。这打破了身份验证流程。

请在下面找到一个例子。这只是一个简单的示例,除了显示服务器如何向客户端发送 cookie 外,它没有任何用处。

后端代码:

import io.micronaut.http.HttpResponse
import io.micronaut.http.MutableHttpResponse
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.micronaut.security.annotation.Secured
import io.micronaut.security.rules.SecurityRule
import io.micronaut.serde.annotation.Serdeable


@Serdeable
class Credentials(
    var username: String,
    var password: String
)


@Controller("/auth")
@Secured(SecurityRule.IS_ANONYMOUS)
class AuthController {

    @Post
    fun authenticate(@Body cred: Credentials): MutableHttpResponse<String> {
        // Check username/password.
        return HttpResponse
            .ok("User: Alex")
            // Here the server is instructing the client to set the cookie.
            .header("Set-Cookie", "auth=123456")
    }
}

客户端实现:

import io.micronaut.http.annotation.*
import io.micronaut.http.client.annotation.Client
import java.util.*


@Client("backend")
interface BackendApi {

    @Post("/auth")
    fun authenticate(username: String, password: String)
}

在上面的示例中,

authenticate
函数接收到带有 cookie 的 HTTP 响应,Micronaut 生成的客户端实现忽略了它。

当将

BackendApi
注入其他 Micronaut 组件时,我希望
BackendApi
在接收到带有
Set-Cookie
标头的 HTTP 响应时存储 cookie,并随所有请求自动发送 cookie。我找不到任何说明如何执行此操作的文档,可能解决方案是使用过滤器。

micronaut setcookie
© www.soinside.com 2019 - 2024. All rights reserved.