1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package com.yaozhitech.spring5.utils;
- import java.io.UnsupportedEncodingException;
- import java.util.Calendar;
- import java.util.Date;
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.JWTVerifier;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.exceptions.JWTDecodeException;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import lombok.extern.slf4j.Slf4j;
- @Slf4j
- public class JwtUtils {
- /**
- * 获得token中的信息无需secret解密也能获得
- * @return token中包含的签发时间
- */
- public static Date getIssuedAt(String token) {
- try {
- DecodedJWT jwt = JWT.decode(token);
- return jwt.getIssuedAt();
- } catch (JWTDecodeException e) {
- return null;
- }
- }
- /**
- * 获得token中的信息无需secret解密也能获得
- * @return token中包含的用户名
- */
- public static String getUsername(String token) {
- try {
- DecodedJWT jwt = JWT.decode(token);
- return jwt.getClaim("username").asString();
- } catch (JWTDecodeException e) {
- return null;
- }
- }
-
- public static String verifyTokenAndGet(String token, String secret) {
- DecodedJWT jwt = null;
- try {
- JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
- jwt = verifier.verify(token);
-
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- return null;
- }
- return jwt.getClaim("username").asString();
- }
- /**
- * 生成签名,expireTime后过期
- * @param username 用户名
- * @param time 过期时间s
- * @return 加密的token
- */
- public static String sign(String username, String salt, long time) {
- try {
- Date date = new Date(System.currentTimeMillis()+time*1000);
- Algorithm algorithm = Algorithm.HMAC256(salt);
- // 附带username信息
- return JWT.create()
- .withClaim("username", username)
- .withExpiresAt(date)
- .withIssuedAt(new Date())
- .sign(algorithm);
- } catch (UnsupportedEncodingException e) {
- return null;
- }
- }
- /**
- * token是否过期
- * @return true:过期
- */
- public static boolean isTokenExpired(String token) {
- Date now = Calendar.getInstance().getTime();
- DecodedJWT jwt = JWT.decode(token);
- return jwt.getExpiresAt().before(now);
- }
- // /**
- // * 生成随机盐,长度32位
- // * @return
- // */
- // public static String generateSalt(){
- // SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
- // String hex = secureRandom.nextBytes(16).toHex();
- // return hex;
- // }
- }
|