运行我的其余服务器时,我的身份验证工作正常。但是,如果我尝试通过测试执行呼叫,则好像每次都跳过身份验证,然后在碰到任何受保护的路由时都会收到401
。我已经验证了应该响应测试而执行的控制器永远不会运行。如果将skipWhen { testing }
添加到jwt
中,则控制器将按预期运行。我的令牌也有效。
Relevant parts of Application.kt
install(Authentication) {
val accessVerifier = appInjector.jwtTokenGenerator().accessVerifier
val refreshVerifier = appInjector.jwtTokenGenerator().refreshVerifier
jwt("access") {
verifier(accessVerifier)
realm = "ktor.io"
validate {
validateToken(it, request)
}
}
jwt("refresh") {
verifier(refreshVerifier)
realm = "ktor.io"
validate {
validateToken(it, request)
}
}
}
routing {
post("$API_V1/auth") { appInjector.signInController().execute(call) }
post("$API_V1/user") { appInjector.signUpController().execute(call) }
get("$API_V1/pagetest") { appInjector.pagedGenreController().execute(call) }
post("$API_V1/multipart") { appInjector.multipartTest().execute(call) }
get("$API_V1/user") { appInjector.userController().execute(call) }
authenticate("access") {
get("$API_V1/me") { appInjector.meController().execute(call) }
delete("$API_V1/token") { appInjector.logoutController().execute(call) }
delete("$API_V1/tokens") { appInjector.invalidateAllTokensController().execute(call) }
post("$API_V1/review") { appInjector.postRevieWController().execute(call) }
}
authenticate("refresh") {
get("$API_V1/refresh") { appInjector.refreshTokenController().execute(call) }
}
}
suspend fun validateToken(cred: JWTCredential, request: ApplicationRequest): Principal? {
val id = cred.payload.getClaim("id").asInt()
val expired = cred.payload.expiresAt.before(Date())
val token = StringUtils.trimAuthHeader(request.parseAuthorizationHeader()?.render())
val valid = appInjector.authHelper().isTokenValid(token)
return if (!expired && valid) {
appInjector.authHelper().findUserById(id)
} else {
null
}
}
Test.kt
@Test
fun testRequest2() {
withTestApplication ({
(environment.config as MapApplicationConfig).apply {
put("ktor.deployment.test", "true")
put("ktor.deployment.port", "8080")
put("ktor.deployment.db_host", "a")
put("ktor.deployment.db_port", "5432")
put("ktor.deployment.db_schema", "c")
put("ktor.deployment.db_username", "d")
put("ktor.deployment.db_password", "e")
put("ktor.deployment.image_upload_dir", "f")
}
module(testing = true)
}) {
handleRequest(HttpMethod.Get, "/api/v1/me") {
addHeader(HttpHeaders.Authorization, "<token>")
}.apply {
assertEquals(HttpStatusCode.OK, response.status())
}
}
}