package com.example.chat.jwt; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import org.springframework.stereotype.Component; public class JWTUtil { private static final String tokenPassword = "uziCjb"; public static String sign(String username) {//用用户名作为被加密的对象 String token; token = JWT.create()//生成jwt令牌,加密过程 .withIssuer("llh") .withClaim("username", username) .sign(Algorithm.HMAC256(tokenPassword)); return token;//返回加密后的token } public static String verify(String token){ JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(tokenPassword)).withIssuer("llh").build();//构建一个jwt解码器 DecodedJWT jwtToken=jwtVerifier.verify(token);//解码 if(token.isEmpty()){//若token为空则返回false拦截 return null; } else { System.out.println("认证通过:"); System.out.println("issuer: " + jwtToken.getIssuer()); System.out.println("username: " + jwtToken.getClaim("username").asString()); return jwtToken.getClaim("username").asString(); } } }