您当前的位置: 首页 >  认证

蓝不蓝编程

暂无认证

  • 0浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

蓝不蓝编程 发布时间:2019-05-04 11:33:54 ,浏览量:0

简要介绍

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 {
        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()
        //TODO:校验用户、密码有效性的代码自己写
        call.respond(Auth.sign(user.name))
    }
}
  1. 对需要认证后才能访问的接口添加认证关键字authenticate(下面样例是用于访问secret页面的)
routing {
    authenticate {
        route("secret") {
            get {
                val user = call.authentication.principal()
                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

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

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0399s