Reputation: 4798
I've successfully included a jwt auth token in my application and able to restrict access to the endpoints. I want to embed the user's ID in the jwt token, but I'm struggling how to implement the jwt verifier in Ktor.
I create a token for the client something like this:
val token = JWT.create().withAudience(audience).withIssuer(issuer).withClaim("userId", "XXX").sign(algorithm)
The route is setup like this. The authentication {} block is run on server startup and does not allow creating a verifier with the userId.
This was derived from the jwt sample:
route("/api") {
authentication {
val jwtVerifier = makeJwtVerifier(issuer, audience)
jwtAuthentication(jwtVerifier, realm) { credential ->
if (credential.payload.audience.contains(audience))
JWTPrincipal(credential.payload)
else
null
}
handle {
// Handle jwt succcess here
}
}
private fun makeJwtVerifier(issuer: String, audience: String): JWTVerifier = JWT
.require(algorithm)
.withAudience(audience)
.withIssuer(issuer)
.build()
What is the correct way to do this? I understand I'd need to create a verifier for each request, but don't really know where to do this nor if that is desirable.
Upvotes: 0
Views: 4387
Reputation: 51461
You should implement it in here. You don't need a verifier that checks user ids.
jwtAuthentication(jwtVerifier, realm) { credential ->
if (credential.payload.audience.contains(audience))
val userId = credential.payload.claims["userId"].asString()
// check if user exists ... if you want
JWTPrincipal(credential.payload)
else
null
}
Upvotes: 1