https://kotlinlang.org logo
Title
a

Avadhut

09/12/2020, 5:55 PM
open class SimpleJWT(val secret: String) {
    private val algorithm = Algorithm.HMAC256(secret)
    val verifier = JWT.require(algorithm).build()
    fun sign(name: String): String = JWT.create().withClaim("name", name).sign(algorithm)
}
fun Application.module() {
    val simpleJwt = SimpleJWT("my-super-secret-for-jwt")
    install(Authentication) {
        jwt {
            verifier(simpleJwt.verifier)
            validate {
                UserIdPrincipal(it.payload.getClaim("name").asString())
            }
        }
    }
    // ...
}
p

Pedro Flores

09/12/2020, 7:32 PM
The withClaim method allows you to add additional information to your JWT Token (see https://jwt.io/ for more info). The UserIdPrincipal will be a provided Principal to your ApplicationCalls if you're properly authenticated.
a

Avadhut

09/12/2020, 7:46 PM
Can you please elaborate UserIdPrincipal?
p

Pedro Flores

09/14/2020, 7:07 AM
See for example on https://ktor.io/samples/feature/auth.html, you can get info about the current logged user. For example there you can access the claims you’ve setted in the JWT token to identify your user/ do some operations based on role values for example
👍 1
a

Avadhut

09/14/2020, 7:10 AM
I'll take look at samples. Thanks alot!