123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- package com.yaozhitech.spring5.utils;
- import java.io.UnsupportedEncodingException;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.Map;
- 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.Claim;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import com.yaozhitech.spring5.common.util.UUIDUtils;
- 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) {
- log.error(e.getMessage(), 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) {
- log.error(e.getMessage(), e);
- return null;
- }
- }
-
- /**
- * 需要密钥才能获得信息
- */
- public static Map<String, Claim> verifyToken(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.getClaims();
- }
-
- 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(){
- return UUIDUtils.generateShortUuid();
- }
- }
|