【摘要】 //引入依赖
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version>
</dependency>
123456
public class JwtUtil {
// token秘钥
public static St…
//引入依赖
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version>
</dependency>
public class JwtUtil {
// token秘钥
public static String SECRET = "djkahfkjhdlkajjdwajdjajwdjdlawjjdwj";
/**
* 生成Jwt的方法
* @param id 用户ID
* @param map 需要加密的数据,可以替换成json或者其他类型
* @return Token String 凭证
*/
public static String createJWT(String id,Map map) {
//设置过期时间
long ttlMillis=96 * 60 * 60 * 1000;//4天
// 签名方法 HS256
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; // 生成Jwt的时间
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis); // 生成秘钥
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); // 设置JWT所存储的信息
JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).signWith(signatureAlgorithm,signingKey); builder.claim("name", map); //存储自定义信息 // 设置过期时间
if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp);
} // 构建JWT并将其序列化为紧凑的URL安全字符串
return builder.compact();
}
/**
* 解析Jwt字符串
*
* @param jwt Jwt字符串
* @return Claims 解析后的对象
*/
public static Claims parseJWT(String jwt) {
return Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(SECRET)).parseClaimsJws(jwt).getBody();
}
/**
* 验证JWT(解析时候调用)
*
* @param jwtStr jwt字符串
* @return JOSNObject 解析结果<br/> */
public static JSONObject validateJWT(String jwtStr) {
JSONObject pojo = new JSONObject();
Claims claims = null;
try { claims = parseJWT(jwtStr); pojo.put("Success", true); pojo.put("Claims", claims);
} /*catch (ExpiredJwtException e) { pojo.put("Success", false); pojo.put("ErrCode", 1005); e.printStackTrace();
} */catch (Exception e) { pojo.put("Success", false); pojo.put("ErrCode", 1004); e.printStackTrace();
}
return pojo;
}
文章来源: blog.csdn.net,作者:yth…,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_43925086/article/details/115866652
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END