美文网首页Kotlin后端开发
ktor结合JWT进行用户身份认证

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

作者: 蓝不蓝编程 | 来源:发表于2019-05-04 11:33 被阅读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<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

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

    相关文章

      网友评论

        本文标题:ktor结合JWT进行用户身份认证

        本文链接:https://www.haomeiwen.com/subject/uzkxoqtx.html