简要介绍
JWT全称:JSON Web Token,是当前使用非常广泛的跨域身份验证方案. 本文介绍在ktor中如何使用JWT.
使用步骤
- build.gradle中添加依赖(maven也类似)
compile "io.ktor:ktor-auth-jwt:$ktor_version"
- 添加认证类:Auth
object Auth {
private const val SECRET_KEY = "secret"
private val algorithm = Algorithm.HMAC512(SECRET_KEY)
private const val issuer = "ktor.io"
private const val validityInMs = 3600*1000 * 10 // 10 hours
fun makeJwtVerifier(): JWTVerifier = JWT
.require(algorithm)
.withIssuer(issuer)
.build()
fun sign(name: String): Map<String, String> {
return mapOf("token" to makeToken(name))
}
private fun makeToken(name: String): String = JWT.create()
.withSubject("Authentication")
.withIssuer(issuer)
.withClaim("name", name)
.withExpiresAt(getExpiration())
.sign(algorithm)
private fun getExpiration() = Date(System.currentTimeMillis() + validityInMs)
}
- 在启动类中启用jwt
private val verifier = Auth.makeJwtVerifier()
install(Authentication) {
jwt {
verifier(verifier)
validate {
UserIdPrincipal(it.payload.getClaim("name").asString())
}
}
}
- 登陆时进行校验,校验成功后返回token
routing {
post("login") {
val user = call.receive<User>()
//TODO:校验用户、密码有效性的代码自己写
call.respond(Auth.sign(user.name))
}
}
- 对需要认证后才能访问的接口添加认证关键字authenticate(下面样例是用于访问secret页面的)
routing {
authenticate {
route("secret") {
get {
val user = call.authentication.principal<UserIdPrincipal>()
call.respondText("hi ${user?.name}, you are authenticated.", contentType = ContentType.Text.Plain)
}
}
}
}
完整源代码
https://github.com/cxyzy1/ktor_jwt
参考资料
https://github.com/joelsaunders/ktor-starter.git
https://github.com/sjcqs/ktor-quotes.git
https://github.com/QAutomatron/ktor-backend.git
https://github.com/AndreasVolkmann/ktor-auth-jwt-sample.git
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」
网友评论