back-end/face-common/src/main/java/com/dkha/common/jwt/JwtHelper.java

98 lines
4.3 KiB
Java
Raw Normal View History

2023-03-23 11:26:57 +08:00
package com.dkha.common.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dkha.common.exception.AuthorityException;
import com.dkha.common.exception.EmployeeException;
import com.dkha.common.systemcode.SystemCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* tokenhttptokentokentoken
*
* @Author: Spring
* Created on 2018/4/23.
*/
public class JwtHelper {
private static final Logger logger = LoggerFactory.getLogger(JwtHelper.class);
/**
* HS256 hashRS256 https://www.cnblogs.com/hehheai/p/6513871.html
*/
private static final String secret = "dk_employment_2019.10.12";
/**
* JWTidexpiresTime
*
*
* iss(Issuser)claima.comclaima.com
* sub(Subject)claimliuyunzhugeclaimliuyunzhuge
* aud(Audience)claim['b.com','c.com']claimb.comc.com
* exp(Expiration time)claim
* nbf(Not Before)claim
* iat(Issued at)maxAgeclaimmaxAge
* jti(JWT ID)claim1claim1
*
* @return
*/
public static String generateJWT(String platform, String userId, String uuid) {
/**设置JWT头部信息*/
Map<String, Object> headerMap = new HashMap<String, Object>(2);
headerMap.put("typ", "JWT");
headerMap.put("alg", "HS256");
String token = null;
try {
token = JWT.create().withHeader(headerMap)
.withClaim(JwtConstantEnum.PLATFORM.code, platform)
.withClaim(JwtConstantEnum.USER_ID.code, userId)
.withClaim(JwtConstantEnum.UUID.code, uuid)
.sign(Algorithm.HMAC256(secret));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
throw new EmployeeException(e);
}
return token;
}
/**
* JWT JWT
* main
* @param token
* @return
*/
public static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
jwt = verifier.verify(token);
return jwt.getClaims();
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
throw new AuthorityException(SystemCode.TOKEN_ERROR.code.toString());
} catch (TokenExpiredException e) {
logger.error(e.getMessage(), e);
throw new AuthorityException(SystemCode.TOKEN_EXPIRED.code.toString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AuthorityException(SystemCode.TOKEN_ERROR.code.toString());
}
}
public static void main(String[] args) {
//JwtHelper.verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.kEZueQ8xZ_FKvlOxfC01bTaW3EqUGV9HJKKeeor6XQ1");
}
}