Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 使用Ktor在auth下测试端点_Kotlin_Ktor - Fatal编程技术网

Kotlin 使用Ktor在auth下测试端点

Kotlin 使用Ktor在auth下测试端点,kotlin,ktor,Kotlin,Ktor,我正在努力为一个在auth(令牌)下的端点编写测试。特别是,在编写测试时,我无法将登录请求与第二个请求链接起来,尽管提供了作为登录请求一部分接收的令牌 LoginEndpoint.kt 现在,有问题的端点 ProfileEndpoint.kt 错误是: expected:<200 OK> but was:<401 Unauthorized> Expected :200 OK Actual :401 Unauthorized 应为:但为: 预计:200行 实际:401

我正在努力为一个在auth(令牌)下的端点编写测试。特别是,在编写测试时,我无法将登录请求与第二个请求链接起来,尽管提供了作为登录请求一部分接收的令牌

LoginEndpoint.kt

现在,有问题的端点

ProfileEndpoint.kt

错误是:

expected:<200 OK> but was:<401 Unauthorized>
Expected :200 OK
Actual   :401 Unauthorized
应为:但为:
预计:200行
实际:401
AuthProvider.kt

开放类AuthProvider(secret:String=System.getenv(Environment.JWT_secret)){
private val algorithm=algorithm.HMAC512(secret)
fun getVerifier():JWTVerifier=JWT
.require(算法)
.withIssuer(应用程序名称)
.build()
fun generateToken(userId:String):String=JWT.create()
.主语(SUBJECT)
.withIssuer(应用程序名称)
.withClaim(索赔,用户ID)
.withExpiresAt(expiresAt())
.符号(算法)
private fun expiresAt()=日期(System.currentTimeMillis()+MILLIES_/天*令牌天数长度)
}
val ApplicationCall.apiUser get()=authentication.principal()
我尝试过使用
cookiesSession
,就像在本文档的示例中一样,但不起作用。任何帮助都将不胜感激

    @Test
    fun `given user exists then returns 200 and token`() {
        val userId = "paco123"
        val token = "magic_token_123"
        withTestApplication({
            givenTestModule()
        }) {
            every { authProvider.generateToken(userId) } answers { token }
            givenPatientExists(userId)
            with(handleRequest(HttpMethod.Post, "/$API_VERSION/login") {
                addHeader("content-type", "application/x-www-form-urlencoded")
                setBody("id=$userId")
            }) {
                assertEquals(HttpStatusCode.OK, response.status())
                assertEquals("{ \"token\": \"magic_token_123\" }", response.content)
            }
        }
    }

    private fun Application.givenTestModule() {
        module(
            testing = true,
            repositoryModule = TestingRepositoryModule,
            authProvider = authProvider
        )
    }
const val PATIENTS_API_ENDPOINT = "$API_VERSION/profile"

@Location(PATIENTS_API_ENDPOINT)
class ProfileEndpoint

fun Route.profileEndpoint(patientsRepository: Repository<Patient>) {
    authenticate("jwt") {
        get<ProfileEndpoint> {
            val apiUser: Patient = call.apiUser!!
            val id = apiUser.id!!
            val patient = patientsRepository.get(id)
            when (patient != null) {
                false -> call.respond(status = HttpStatusCode.NotFound, message = "Patient with id $id does not exist")
                true -> call.respond(status = HttpStatusCode.OK, message = patient.map())
            }
        }
    }
}
    @Test
    fun `given user is logged in then returns 200 and profile`() {
        val userId = "paco123"
        val token = "magic_token_123"
        withTestApplication({
            givenTestModule()
        }) {
            every { authProvider.generateToken(userId) } answers { token }
            givenPatientExists(userId)

            handleRequest(HttpMethod.Post, "/$API_VERSION/login") {
                addHeader("content-type", "application/x-www-form-urlencoded")
                setBody("id=$userId")
            }

            handleRequest(HttpMethod.Get, "/$API_VERSION/profile") {
                addHeader("Authorization", "Bearer $token")
            }.apply {
                assertEquals(HttpStatusCode.OK, response.status())
            }
        }
    }
expected:<200 OK> but was:<401 Unauthorized>
Expected :200 OK
Actual   :401 Unauthorized
open class AuthProvider(secret: String = System.getenv(Environment.JWT_SECRET)) {
    private val algorithm = Algorithm.HMAC512(secret)

    fun getVerifier(): JWTVerifier = JWT
        .require(algorithm)
        .withIssuer(APP_NAME)
        .build()

    fun generateToken(userId: String): String = JWT.create()
        .withSubject(SUBJECT)
        .withIssuer(APP_NAME)
        .withClaim(CLAIM, userId)
        .withExpiresAt(expiresAt())
        .sign(algorithm)

    private fun expiresAt() = Date(System.currentTimeMillis() + MILLIES_PER_DAY * TOKEN_DAYS_LENGTH)
}

val ApplicationCall.apiUser get() = authentication.principal<Patient>()