token
导入依赖
<!-- jwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- jdk 9 以后已经移除,使用时需要单独导包 --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency>
package com.exam.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; import java.util.Date; import java.util.UUID; /** * JWT 工具类 */ public class JwtUtil { // 有效期,1小时 public static final Long JWT_TTL = 60 * 60 * 1000L; // 设置秘钥铭文(盐) public static final String JWT_KEY = "WDsv234s"; // 生成令牌 public static String getUUID() { String token = UUID.randomUUID().toString().replaceAll("-", ""); return token; } /** * 生成 jwt * * @param subject token中要存放的数据(json格式) * @param ttlMillis token超时时间 * @return */ public static String createJWT(String subject, Long ttlMillis) { JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID()); String s = builder.compact(); return s; } // 生成JWT 的业务逻辑代码 private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; SecretKey secretKey = generalKey(); // 获取到系统当前时间戳 Long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); if (ttlMillis == null) { ttlMillis = JwtUtil.JWT_TTL; } Long expMillis = nowMillis + ttlMillis; Date expDate = new Date(expMillis); return Jwts.builder() .setId(uuid) // 唯一的id .setSubject(subject) // 主题 可以是JSON数据 .setIssuer("xx") // 签发者 .setIssuedAt(now) // 签发时间 .signWith(signatureAlgorithm, secretKey) // 使用HS256 加密算法签名,第二个参数为秘钥 .setExpiration(expDate); } /** * 创建token * @param id * @param subject * @param ttlMillis * @return */ public static String createJWT(String id, String subject, Long ttlMillis){ JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id); return builder.compact(); } /** * 生成加密后的秘钥 secretKry * @return */ public static SecretKey generalKey(){ byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); SecretKey key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES"); return key; } /** * 解析 * @param jwt * @return */ public static Claims parseJWT(String jwt) throws Exception{ SecretKey secretKey = generalKey(); return Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(jwt) .getBody(); } }
标签:return,String,jwt,SpringSecurity,---,static,import,subject,ttlMillis From: https://www.cnblogs.com/wangdch/p/18369848