|
|
@@ -0,0 +1,64 @@
|
|
|
+package com.mrxu.framework.boot.token;
|
|
|
+
|
|
|
+import com.auth0.jwt.JWT;
|
|
|
+import com.auth0.jwt.JWTCreator;
|
|
|
+import com.auth0.jwt.JWTVerifier;
|
|
|
+import com.auth0.jwt.algorithms.Algorithm;
|
|
|
+import com.auth0.jwt.interfaces.DecodedJWT;
|
|
|
+import com.mrxu.framework.boot.entity.BusinessException;
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+
|
|
|
+import java.io.UnsupportedEncodingException;
|
|
|
+import java.util.Date;
|
|
|
+
|
|
|
+
|
|
|
+public class JwtUtil {
|
|
|
+
|
|
|
+ private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);
|
|
|
+
|
|
|
+ public static String sign(String key,String value,long expireTime,String secret) {
|
|
|
+ try {
|
|
|
+ Date date = new Date(System.currentTimeMillis() + expireTime);
|
|
|
+ Algorithm algorithm = Algorithm.HMAC256(secret);
|
|
|
+ JWTCreator.Builder builder = JWT.create();
|
|
|
+ builder.withClaim(key,value);
|
|
|
+ builder.withExpiresAt(date);
|
|
|
+ return builder.sign(algorithm);
|
|
|
+ }
|
|
|
+ catch (UnsupportedEncodingException e) {
|
|
|
+ logger.error("JWT 密码 {} 编码错误:{}",secret,e);
|
|
|
+ throw new BusinessException("错误编码错误");
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void verify(String token,String secret) {
|
|
|
+ try {
|
|
|
+ Algorithm algorithm = Algorithm.HMAC256(secret);
|
|
|
+ JWTVerifier verifier = JWT.require(algorithm).build();
|
|
|
+ verifier.verify(token);
|
|
|
+ }
|
|
|
+ catch (UnsupportedEncodingException e) {
|
|
|
+ logger.error("JWT 密码 {} 编码错误:{}",secret,e);
|
|
|
+ throw new BusinessException("错误编码错误");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String getValue(String token, String key) {
|
|
|
+ DecodedJWT jwt = JWT.decode(token);
|
|
|
+ return jwt.getClaim(key).asString();
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ String token = sign("memberId","92341398766528923",
|
|
|
+ 10*1000,"mrxu");
|
|
|
+ logger.info("生成token:{}",token);
|
|
|
+ verify(token,"mrxu");
|
|
|
+ String value = getValue(token,"memberId");
|
|
|
+ logger.info("获取token值:{}",value);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|