赞
踩
import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JwtTokenUtils { //签发者 private static final String ISS = "SUPERMAN"; //过期时间15分钟 private static final long EXPIRATION_15_MIN = 900L; //过期时间1小时 private static final long EXPIRATION_ONE_HOUR = 3600L; //过期时间1天 private static final long EXPIRATION_ONE_DAY = 604800L; /** * 生成Token * @param userInfoMap * @param secretKey 用于签名的私钥 * @param expireTimeType * @author yq * @return String */ public static String createToken(Map<String,Object> userInfoMap, String secretKey , int expireTimeType){ //add by yangqing --生成Token 20200730 start //过期时间 0:小时 1:分钟 2:天 long expireTime = 0; if (expireTimeType == 0){ expireTime = EXPIRATION_ONE_HOUR; } else if(expireTimeType == 1){ expireTime = EXPIRATION_15_MIN; }else { expireTime = EXPIRATION_ONE_DAY; } //Jwt头 Map<String,Object> header = new HashMap<String, Object>(); header.put("typ", "JWT"); header.put("alg", "HS256"); Map<String,Object> claims = new HashMap<String, Object>(); //自定义有效载荷部分 claims.put("userId", userInfoMap.get("userId")); claims.put("userName", userInfoMap.get("userName")); return Jwts.builder() //发证人 超级经理人 .setIssuer(ISS) //Jwt头 .setHeader(header) //有效载荷 .setClaims(claims) //设定签发时间 .setIssuedAt(new Date()) //设定过期时间 .setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000)) //使用HS256算法签名,PRIVATE_KEY为签名密钥 .signWith(SignatureAlgorithm.HS256,secretKey) .compact(); //add by yangqing --生成Token 20200730 end } /** * 验证Token,返回数据只有userId和auserName的Map对象 * @param token * @param secretKey 用于签名的私钥 * @author yq * @return */ public static Map<String,Object> checkToken(String token, String secretKey){ //add by yangqing --验证Token,返回数据只有userId和auserName的Map对象 20200730 start Map<String,Object> userInfoMap = new HashMap<String, Object>(); //解析token后,从有效载荷取出值 Claims claims = getClaimsFromToken(token, secretKey); if(null == claims){ return userInfoMap; } Object userId = getClaimsFromToken(token, secretKey).get("userId"); Object userName = getClaimsFromToken(token, secretKey).get("userName"); //封装为Map对象 userInfoMap.put("userId", userId); userInfoMap.put("userName", userName); return userInfoMap; //add by yangqing --验证Token,返回数据只有userId和auserName的Map对象 20200730 end } /** * 获取有效载荷 * @param token * @param secretKey 用于签名的私钥 * @author yq * @return */ public static Claims getClaimsFromToken(String token, String secretKey){ //add by yangqing --获取有效载荷 20200730 start Claims claims = null; try { claims = Jwts.parser() //设定解密私钥 .setSigningKey(secretKey) //传入Token .parseClaimsJws(token) //获取载荷类 .getBody(); }catch (ExpiredJwtException e){ return null; } return claims; //add by yangqing --获取有效载荷 20200730 end } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。