|
@@ -1,101 +0,0 @@
|
|
|
-package com.alvin.util;
|
|
|
-
|
|
|
-import com.auth0.jwt.JWT;
|
|
|
-import com.auth0.jwt.JWTCreator;
|
|
|
-import com.auth0.jwt.algorithms.Algorithm;
|
|
|
-import com.auth0.jwt.interfaces.Claim;
|
|
|
-import com.auth0.jwt.interfaces.DecodedJWT;
|
|
|
-import org.springframework.util.Assert;
|
|
|
-
|
|
|
-import java.io.UnsupportedEncodingException;
|
|
|
-import java.util.Date;
|
|
|
-import java.util.HashMap;
|
|
|
-import java.util.Map;
|
|
|
-
|
|
|
-/**
|
|
|
- * jwt工具类
|
|
|
- * <dependency>
|
|
|
- * <groupId>com.auth0</groupId>
|
|
|
- * <artifactId>java-jwt</artifactId>
|
|
|
- * <version>3.2.0</version>
|
|
|
- * </dependency>
|
|
|
- *
|
|
|
- * @author mlamp
|
|
|
- * @date 2022/05/22
|
|
|
- */
|
|
|
-public class JwtUtil {
|
|
|
- private static String SECRET = "123SDFEEdfdeFDRE";
|
|
|
-
|
|
|
- /**
|
|
|
- * 过期时间1000 60 秒 60 分钟 24 小时 10 天
|
|
|
- */
|
|
|
- private static final Long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 30L;
|
|
|
-
|
|
|
- private static Algorithm algorithm;
|
|
|
-
|
|
|
- static {
|
|
|
- try {
|
|
|
- algorithm = Algorithm.HMAC256(SECRET);
|
|
|
- } catch (UnsupportedEncodingException e) {
|
|
|
- e.printStackTrace();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 校验token是否正确,是否过期
|
|
|
- *
|
|
|
- * @param token 密钥
|
|
|
- * @return 是否正确
|
|
|
- */
|
|
|
- public static Boolean verify(String token) {
|
|
|
- try {
|
|
|
- JWT.require(algorithm).build().verify(token);
|
|
|
- return true;
|
|
|
- } catch (Exception e) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 生成签名
|
|
|
- *
|
|
|
- * @param map 信息
|
|
|
- * @return 加密的token
|
|
|
- */
|
|
|
- public static String sign(HashMap<String, String> map) {
|
|
|
- Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
|
|
|
- JWTCreator.Builder builder = JWT.create();
|
|
|
- for (Map.Entry<String, String> entry : map.entrySet()) {
|
|
|
- builder.withClaim(entry.getKey(), entry.getValue());
|
|
|
- }
|
|
|
- return builder.withExpiresAt(date).sign(algorithm);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 获得token中的信息
|
|
|
- *
|
|
|
- * @return ShiroUserBean
|
|
|
- */
|
|
|
- public static HashMap<String, String> unSign(String token) {
|
|
|
- Assert.isTrue(verify(token), "token验证失败");
|
|
|
- HashMap<String, String> map = new HashMap<>();
|
|
|
- DecodedJWT jwt = JWT.decode(token);
|
|
|
- for (Map.Entry<String, Claim> entry : jwt.getClaims().entrySet()) {
|
|
|
- String value = entry.getValue().asString();
|
|
|
- if (value != null) {
|
|
|
- map.put(entry.getKey(), value);
|
|
|
- }
|
|
|
- }
|
|
|
- return map;
|
|
|
- }
|
|
|
-
|
|
|
- public static void main(String[] args) {
|
|
|
- HashMap<String, String> map = new HashMap<>();
|
|
|
- map.put("name", "小明");
|
|
|
- String token = sign(new HashMap<String, String>() {{
|
|
|
- put("name", "小明");
|
|
|
- put("age", "18");
|
|
|
- }});
|
|
|
- System.out.println(unSign(token));
|
|
|
- }
|
|
|
-}
|