1.首先引入maven依赖
com.auth0 java-jwt3.4.0 com.alibaba fastjson1.2.78
2.写一个JWT的工具类
import com.alibaba.fastjson.JSON; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.qcby.xmfs.boot.entity.User; import lombok.extern.slf4j.Slf4j; import java.util.*; @Slf4j public class JwtUtilBak { //过期时间 2min private static final int EXPIRE_TIME = 2; //私钥 自定义 private static final String TOKEN_SECRET = "privateKey"; // 普通常量 private static final String CLAIM_USER = "claimUser"; public static String createToken(User user) { Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.MINUTE,EXPIRE_TIME); Date expiresDate = nowTime.getTime(); String userJson = JSON.toJSonString(user); return JWT.create() .withAudience(user.getId()+"") //签发对象 .withIssuedAt(new Date()) //发行时间 .withExpiresAt(expiresDate) //有效时间 // 存储用户信息 => json转化 ,序列化 .withClaim(CLAIM_USER,userJson) //载荷 => 附带信息:比如用户信息 .sign(Algorithm.HMAC256(user.getId()+TOKEN_SECRET)); //加密 } public static boolean verifyToken(String token, String secret) { try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret+TOKEN_SECRET)).build(); verifier.verify(token); } catch (Exception e) { log.error(e.getMessage(),e); //效验失败 //自定义的一个异常 return false; } return true; } public static String getAudience(String token) { String audience = null; try { audience = JWT.decode(token).getAudience().get(0); } catch (Exception j) { log.error(j.getMessage(),j); return null; } return audience; } public static User getUser(String token) { User user = null; try { String userJson = JWT.decode(token).getClaim(CLAIM_USER).asString(); user = JSON.parseObject(userJson,User.class); } catch (JWTDecodeException j) { log.error(j.getMessage(),j); return null; } return user; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)