package com.gkhy.assess.common.utils;
|
|
import cn.hutool.crypto.digest.DigestUtil;
|
import com.auth0.jwt.JWT;
|
import com.auth0.jwt.JWTVerifier;
|
import com.auth0.jwt.algorithms.Algorithm;
|
import com.auth0.jwt.exceptions.JWTDecodeException;
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
import com.gkhy.assess.common.exception.ApiException;
|
import org.apache.commons.lang3.StringUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.util.Date;
|
|
/**
|
* JwtToken生成的工具类
|
* JWT token的格式:header.payload.signature
|
* header的格式(算法、token的类型):
|
* {"alg": "HS512","typ": "JWT"}
|
* payload的格式(用户名、创建时间、生成时间):
|
* {"sub":"wang","created":1489079981393,"exp":1489684781}
|
* signature的生成算法:
|
* HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
|
*/
|
public class JwtTokenUtil {
|
private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
|
|
public static final String USER_LOGIN_TOKEN="Authorization";
|
|
public static final String CLAIM_KEY_USERNAME = "sub";
|
public static final String CLAIM_KEY_CREATED = "created";
|
|
public static String SECRET="nms-secret";
|
|
public static String tokenHead="";
|
|
/**Token有效期为7天(Token在reids中缓存时间为两倍)*/
|
public static final long EXPIRATION=(7 * 12) * 60 * 60 * 1000; //JWT的超期限时间(60*60*24*7)
|
|
/**
|
* 校验token是否正确
|
* @param token
|
* @param username
|
* @param secret 用户密码
|
* @return
|
*/
|
public static boolean verify(String token,String username,String secret){
|
try {
|
Algorithm algorithm = Algorithm.HMAC256(secret);
|
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
|
DecodedJWT jwt = verifier.verify(token);
|
return true;
|
}catch (Exception e){
|
return false;
|
}
|
}
|
|
/**
|
* 获取token中的信息 无需secret解密也能获得
|
* @param token
|
* @return
|
*/
|
public static String getUsername(String token){
|
try {
|
DecodedJWT jwt = JWT.decode(token);
|
return jwt.getClaim("username").asString();
|
}catch (JWTDecodeException e){
|
return null;
|
}
|
}
|
|
/**
|
* 生成签名
|
* @param username
|
* @param secret
|
* @return
|
*/
|
public static String sign(String username,String secret){
|
Date date=new Date(System.currentTimeMillis()+EXPIRATION*1000);
|
Algorithm algorithm=Algorithm.HMAC256(secret);
|
return JWT.create().withClaim("username",username).withExpiresAt(date).sign(algorithm);
|
}
|
|
/**
|
* 根据request中的token获取用户账号
|
*
|
* @param request
|
* @return
|
* @throws ApiException
|
*/
|
public static String getUserNameByToken(HttpServletRequest request) throws ApiException {
|
String accessToken = request.getHeader(USER_LOGIN_TOKEN);
|
String username = getUsername(accessToken);
|
if (StringUtils.isEmpty(username)) {
|
throw new ApiException("未获取到用户");
|
}
|
return username;
|
}
|
|
|
/**
|
* md5加密
|
* @param token
|
* @return
|
*/
|
public static String md5Encode(String token){
|
|
return DigestUtil.md5Hex(token);
|
}
|
|
|
|
}
|