jwt解决登入才有权限访问的问题
第一步
引入依赖
<!-- JWT -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.3</version>
</dependency>
第二步
编写jwt工具类
package com.mysteel.app.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JwtTokenUtil {
//过期时间 15 天
private static final Long EXPIRE_TIME = 15 * 24 * 60 * 60 * 1000L;
// private static final Long EXPIRE_TIME = 30 * 60 * 1000L;
//私钥
private static final String TOKEN_SECRET = "cb30edfe27754e3faafaeca14d98122d";
/**
* 生成签名,15 天过期
*
* @param **username**
* @param **password**
* @return
*/
public static String sign(String userInfo) {
try {
// 设置过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥和加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头部信息
Map< String, Object > header = new HashMap<>(2);
header.put("Type", "Jwt");
header.put("alg", "HS256");
// 返回token字符串
return JWT.create()
.withHeader(header)
.withClaim("userInfo", userInfo)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
log.error("JWT生成签名错误!!!");
return null;
}
}
/**
* 检验签名token是否正确
*
* @param **token**
* @return
*/
public static String verify(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
// 校验token
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("userInfo").asString();
} catch (Exception e) {
log.error("检验token失败", e);
return null;
}
}
public static void main(String[] args) {
// String authToken = UUID.randomUUID().