0

我有以下我正在尝试测试的控制器

@Secured(SecurityRule.IS_AUTHENTICATED)
@Controller
class UserController(private val userService: UserService) {
    @Get("/principal")
    fun getPrincipal(principal: Principal): Principal = principal
}

我的测试如下所示

class Credentials(val username: String, val password: String)

class LoginResponse(
    @JsonProperty("access_token") val accessToken: String,
    @JsonProperty("expires_in") val expiresIn: Int,
    @JsonProperty("refresh_token") val refreshToken: String,
    @JsonProperty("token_type") val tokenType: String,
    @JsonProperty("username") val username: String)

@Client("/")
interface Client {
    @Post("/login")
    fun login(@Body credentials: Credentials): LoginResponse

    @Get("/principal")
    fun getPrincipal(@Header authorizationHeader: String): Principal
}

@MicronautTest
internal class UserControllerTest {
    @Inject
    lateinit var authenticationConfiguration: AuthenticationConfiguration

    @Inject
    lateinit var client: Client

    @Test
    fun getPrincipal() {
        val credentials = Credentials(authenticationConfiguration.testUserEmail, authenticationConfiguration.testUserPassword)
        val loginResponse = client.login(credentials)
        val authorizationHeader = "Authorization:Bearer ${loginResponse.accessToken}"
        val principal = client.getPrincipal(authorizationHeader)
    }
}

登录工作正常。我得到一个不记名令牌,authorizationHeader 看起来很好。但是调用client.getPrincipal(authorizationHeader)失败了io.micronaut.http.client.exceptions.HttpClientResponseException: Unauthorized

任何线索出了什么问题?

4

1 回答 1

0

事实证明,我可以将我的客户声明如下。通过命名参数以匹配实际的 http 标头。

@Client("/")
interface Client {
    ...
    @Get("/principal")
    fun getPrincipal(@Header authorization: String): Principal
}

但是也可以让 @Header 注释接受一个参数来指定要定位的 http 标头

@Client("/")
interface Client {
    ...
    @Get("/principal")
    fun getPrincipal(@Header("Authorization") authorizationValue: String): Principal
}
于 2019-12-10T13:52:42.540 回答