Add JWT auth
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package be.vandewalleh.auth
|
||||
|
||||
import be.vandewalleh.kodein
|
||||
import io.ktor.application.Application
|
||||
import io.ktor.application.install
|
||||
import io.ktor.auth.Authentication
|
||||
import io.ktor.auth.UserIdPrincipal
|
||||
import io.ktor.auth.jwt.jwt
|
||||
import org.kodein.di.generic.instance
|
||||
|
||||
fun Application.authenticationModule() {
|
||||
install(Authentication) {
|
||||
jwt {
|
||||
val simpleJwt: SimpleJWT by kodein.instance()
|
||||
verifier(simpleJwt.verifier)
|
||||
validate {
|
||||
UserIdPrincipal(it.payload.getClaim("name").asString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package be.vandewalleh.auth
|
||||
|
||||
import com.auth0.jwt.JWT
|
||||
import com.auth0.jwt.JWTVerifier
|
||||
import com.auth0.jwt.algorithms.Algorithm
|
||||
import java.util.*
|
||||
|
||||
class SimpleJWT(secret: String) {
|
||||
private val validityInMs = 36_000_00 * 1
|
||||
private val algorithm = Algorithm.HMAC256(secret)
|
||||
|
||||
val verifier: JWTVerifier = JWT.require(algorithm).build()
|
||||
fun sign(name: String): String = JWT.create()
|
||||
.withClaim("name", name)
|
||||
.withExpiresAt(getExpiration())
|
||||
.sign(algorithm)
|
||||
|
||||
private fun getExpiration() = Date(System.currentTimeMillis() + validityInMs)
|
||||
}
|
||||
Reference in New Issue
Block a user