我有以下要测试的控制器
@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
任何提示出了什么问题吗?
答案 0 :(得分: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
}