https://kotlinlang.org logo
Title
p

pascal_le_merrer

08/22/2020, 7:54 AM
Hello. I managed to set up JWT authentication in ktor. It works. However I dont see how to get the claims containd in the token when processing a request. How can I get them?
p

Pedro Flores

08/22/2020, 8:57 AM
If I'm not mistaken, you can get them inside your call by accessing the Principal property
p

pascal_le_merrer

08/22/2020, 9:41 AM
That's what I did before replacing basic auth with JWT. I got it using
val principal: UserIdPrincipal? = call.authentication.principal<UserIdPrincipal>()
But with JWT, call.authentication.principal is null
I found the solution. I have to get the claim like this:
val principal: JWTPrincipal? = call.authentication.principal<JWTPrincipal>()
return principal!!.payload.getClaim("my_claim").asString()
p

Pedro Flores

08/22/2020, 10:25 AM
Glad that you've found it, on a test I wrote i'm able to get it directly from the ApplicationCall.principal, but I don't know how your validate lambda is implemented
p

pascal_le_merrer

08/24/2020, 7:54 AM
I’m interested in your validate lambda, @Pedro Flores. Could you post it please?
Mine looks like this:
fun validateCredential(jwtCredential: JWTCredential): Principal? {

    val sessionId = jwtCredential.payload.getClaim("sessionId").asString()

    if (isValidSessionId(cuid, sessionId)) {
        return JWTPrincipal(jwtCredential.payload)
    }

    return null
}
p

Pedro Flores

08/24/2020, 8:05 AM
Well it’s quite similar, the difference is that I have an extended Principal but still it should be working as the documentation intended :)
p

pascal_le_merrer

08/24/2020, 10:04 AM
That’s the point I missed. It’s much simpler with a class extending Principal. Thanks @Pedro Flores! 👍