【问题标题】:Testing of secured controller安全控制器的测试
【发布时间】:2019-12-10 08:18:11
【问题描述】:

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

@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

有什么线索吗?

【问题讨论】:

    标签: kotlin micronaut micronaut-client


    【解决方案1】:

    事实证明,我可以将我的客户声明如下。通过命名参数以匹配实际的 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 2017-06-08
      • 2019-06-22
      • 1970-01-01
      • 2016-11-25
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多