mirror of
https://gitee.com/lab1024/smart-admin.git
synced 2025-11-22 18:36:52 +08:00
add jwt decode and remove shopping cart API parameter memberId
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package net.lab1024.smartadmin.util;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class SmartJWTUtil {
|
||||
|
||||
/**
|
||||
* 过期时间一天
|
||||
*/
|
||||
private static final int EXPIRE_SECONDS = 1 * 24 * 3600;
|
||||
/**
|
||||
* jwt加密字段
|
||||
*/
|
||||
private static final String CLAIM_ID_KEY = "id";
|
||||
|
||||
//设置过期时间
|
||||
private static final long EXPIRE_DATE = 30 * 60 * 100000;
|
||||
//token秘钥
|
||||
private static final String TOKEN_SECRET = "smart-admin-jwt-key";
|
||||
|
||||
|
||||
|
||||
|
||||
public static String generateToken(String userId) {
|
||||
String token;
|
||||
try {
|
||||
//过期时间
|
||||
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
|
||||
//秘钥及加密算法
|
||||
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
|
||||
//设置头部信息
|
||||
Map<String, Object> header = new HashMap<>();
|
||||
header.put("typ", "JWT");
|
||||
header.put("alg", "HS256");
|
||||
//携带UserId信息,生成签名
|
||||
token = JWT.create()
|
||||
.withHeader(header)
|
||||
.withClaim(CLAIM_ID_KEY, userId)
|
||||
.withExpiresAt(date)
|
||||
.sign(algorithm);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* JWT解密
|
||||
*
|
||||
* @Author: RZH
|
||||
* @Date: 2020/4/6 9:30
|
||||
*/
|
||||
public static String decodeToken(final String token) {
|
||||
String userId = null;
|
||||
try {
|
||||
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
|
||||
.build();
|
||||
DecodedJWT jwt = verifier.verify(token);
|
||||
if (jwt != null) {
|
||||
userId = jwt.getClaim(CLAIM_ID_KEY).asString();
|
||||
}
|
||||
} catch (JWTVerificationException exception) {
|
||||
exception.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String token = SmartJWTUtil.generateToken("844350");
|
||||
System.out.println(SmartJWTUtil.decodeToken(token));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user