JWT token生成
需求:生成和原来生成的token兼容的token
注意点:1.token的格式一样 2.算法一样 3.密钥一样
JWT token生成例子
//生成token,验证token工具类
@Component
class Token {/*** token 密钥*/private val JWT_SECRET = "test"/*** token 过期时间(30天)*/private val calendarField = Calendar.DATEprivate val calendarInterval = 30private val algorithm = Algorithm.HMAC256(JWT_SECRET)// header Mapprivate val map: MutableMap<String, Any> = HashMap()private fun createTokenBuilder(): JWTCreator.Builder {/** 加密方式 */map["alg"] = "HS256"map["typ"] = "JWT"// 设置过期时间val nowTime = Calendar.getInstance()nowTime.add(calendarField, calendarInterval) //前者为时间单位,后者时间数量val expiresDate = nowTime.timereturn JWT.create().withExpiresAt(expiresDate)}/*** 生成token** @param* @return*/fun createToken(uid: String?): String { //token保存的数据val builder = createTokenBuilder()return builder.withClaim("jti", uid).sign(algorithm)}// 解析fun verifyToken(token: String?): DecodedJWT? {var jwt: DecodedJWT? = nulltry {//解析方式和密钥val verifier = JWT.require(algorithm).build()val decodedJWT = JWT.decode(token)jwt = verifier.verify(decodedJWT)} catch (e: Exception) {e.printStackTrace()// token 校检失败}return jwt}}//配置token拦截器
class JwtInterceptor : HandlerInterceptor {@Autowiredprivate lateinit var tokenService: Tokenoverride fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {// 从 http 请求头中取出 tokenval token = request.getHeader("refresh-token")println(token)// 如果不是映射到方法直接通过if (handler !is HandlerMethod) {return true}if (StringUtils.isBlank(token)) {throw RuntimeException("无token,请重新登录")}// 验证 tokentry {if (tokenService.verifyToken(token) == null) throw RuntimeException("token无效")println("token校验")} catch (e: JWTVerificationException) {throw RuntimeException("token失效,请重新登录")}return true}
}
参考网站:生成的token解析
使用JWT生成Token令牌