token 模板s
1:

package com.bihu.security.security; import io.jsonwebtoken.CompressionCodecs; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import java.util.Date; @Component public class TokenManager { //Token 有效时间,单位:秒 private final long TOKEN_EXPIRE_TIME = 60 * 60 * 24; //秘钥编码 private final String TOKEN_KEY = "xxxxxxxx"; //根据用户名生成Token public String createToken(String username) { //生成Token String token = Jwts.builder().setSubject(username) //设置主题 .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME * 1000)) //设置过期时间 .signWith(SignatureAlgorithm.HS512, TOKEN_KEY) //设置签名算法和秘钥 .compressWith(CompressionCodecs.GZIP) //设置压缩算法 .compact(); //生成Token return token; } // 解析Token public String parseToken(String token) { String userInfo = Jwts.parser().setSigningKey(TOKEN_KEY).parseClaimsJws(token).getBody().getSubject(); return userInfo; } // 删除Token public void deleteToken(String token) { Jwts.parser().setSigningKey(TOKEN_KEY).parseClaimsJws(token).getBody().getSubject(); } public static void main(String[] args) { TokenManager tokenManager = new TokenManager(); String token = tokenManager.createToken("65456讲话稿发原图沸腾鱼"); System.out.println(token); String userInfo = tokenManager.parseToken(token); System.out.println(userInfo); } }
2.

package com.bihu.security.security; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.UUID; public class JWTUtils { private static final String SECRET = "23e9b42d-2b8d-4df5-a9ba-f3cc25136048"; private static final long EXPIRE = 60 * 60 * 24 * 1000; public static String createToken(Integer id, String email, String role) { Date date = new Date(); return JWT.create() .withJWTId(UUID.randomUUID().toString()) .withIssuer("yingcai-hr") .withIssuedAt(date) .withExpiresAt(new Date(date.getTime()+EXPIRE)) .withClaim("id", id) .withClaim("email", email) .withClaim("role", role) .sign(Algorithm.HMAC384(SECRET.getBytes(StandardCharsets.UTF_8))); } public static DecodedJWT verity(String token) { return JWT.require(Algorithm.HMAC384(SECRET.getBytes(StandardCharsets.UTF_8))).build().verify(token); } }
本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/16373819.html