ktor结合JWT进行用户身份认证

简要介绍

JWT全称:JSON Web Token,是当前使用非常广泛的跨域身份验证方案. 本文介绍在ktor中如何使用JWT.

使用步骤

  1. build.gradle中添加依赖(maven也类似)
compile "io.ktor:ktor-auth-jwt:$ktor_version"
  1. 添加认证类: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)

}
  1. 在启动类中启用jwt
private val verifier = Auth.makeJwtVerifier()
install(Authentication) {
        jwt {
            verifier(verifier)
            validate {
                UserIdPrincipal(it.payload.getClaim("name").asString())
            }
        }
    }
  1. 登陆时进行校验,校验成功后返回token
routing {
    post("login") {
        val user = call.receive<User>()
        //TODO:校验用户、密码有效性的代码自己写
        call.respond(Auth.sign(user.name))
    }
}
  1. 对需要认证后才能访问的接口添加认证关键字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

点击关注专栏,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值