package com.zhhs.app.utils; import com.alibaba.fastjson.JSON; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author 贰拾叁 * @date 2020/7/7 16:18 * @desc: * @use: * @ex: */ @Slf4j public class JwtHelper { //签名秘钥 public static final String BASE64SECRET = "************************"; //过期时间 1天 public static final long EXPIRESSECOND = 1 * 24 * 60 * 60 * 1000; public static String generateJWT(String userId, String openId) { //签名算法,选择SHA-256 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //获取当前系统时间 long nowTimeMillis = System.currentTimeMillis(); Date now = new Date(nowTimeMillis); //将BASE64SECRET常量字符串使用base64解码成字节数组 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(BASE64SECRET); //使用HmacSHA256签名算法生成一个HS256的签名秘钥Key Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 Map<String, Object> headMap = new HashMap<>(); headMap.put("alg", SignatureAlgorithm.HS256.getValue()); headMap.put("typ", "JWT"); JwtBuilder builder = Jwts.builder().setHeader(headMap) //用户id .claim("userId", AesUtil.aesEncrypt(userId)) .claim("openId", AesUtil.aesEncrypt(openId)) //签名 .signWith(signatureAlgorithm, signingKey); //添加Token过期时间 //超时毫秒数1天 long expMillis = nowTimeMillis + EXPIRESSECOND; Date expDate = new Date(expMillis); builder.setExpiration(expDate).setNotBefore(now); //签名颁发者 builder.setIssuer("ICF"); return builder.compact(); } private static Claims parseJWT(String jsonWebToken) { Claims claims = null; try { if (StringUtils.isNotBlank(jsonWebToken)) { //解析jwt claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(BASE64SECRET)) .parseClaimsJws(jsonWebToken).getBody(); } else { log.warn("[JWTHelper]-json web token 为空"); } } catch (Exception e) { log.error("[JWTHelper]-JWT解析异常:可能因为token已经超时或非法token"); } return claims; } public static String validateToken(String jsonWebToken) { Map<String, Object> retMap = null; Claims claims = parseJWT(jsonWebToken); if (claims != null) { //解密客户编号 try { String userId = AesUtil.aesDecrypt((String) claims.get("userId")); String openId = AesUtil.aesDecrypt((String) claims.get("openId")); retMap = new HashMap<>(); retMap.put("userId", userId); retMap.put("openId", openId); } catch (Exception e) { log.error("解密数据出错={}", e.getMessage()); e.printStackTrace(); } } return retMap != null ? JSON.toJSONString(retMap) : null; } }
也可以直接使用https://www.hutool.cn/docs/#/封装好的工具类