导入依赖
com.auth0 java-jwt3.4.0
配置文件
# token配置
token:
jwt:
# 令牌自定义标识
header: Authorization
# 令牌密钥
secret: ">?N<:{LWPWXX#$%()(#*!()!KL<>
Jwt工具类,包括token的生成,token的验证并返回存在负载中的用户信息
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.auth0.jwt.JWTCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
@Component
public class JwtUtils {
public static String SECRET = "";
public static final int calendarField = Calendar.MINUTE;
public static int calendarInterval = 30;
@Value("${token.jwt.secret}")
public void setSECRET(String SECRET) {
JwtUtils.SECRET = SECRET;
}
@Value("${token.jwt.expireTime}")
public void setCalendarInterval(int calendarInterval) {
JwtUtils.calendarInterval = calendarInterval;
}
public static String createToken(Map map) {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(calendarField, calendarInterval);
Date expiresDate = nowTime.getTime();
// header Map
Map header = new HashMap<>();
header.put("alg", "HS256");
header.put("typ", "JWT");
// 创建 token
// param backups {iss:Service, aud:APP}
JWTCreator.Builder builder = JWT.create().withHeader(header); // header
map.forEach(builder::withClaim); // payload
// 指定token过期签名 和 签名
return builder.withExpiresAt(expiresDate).sign(Algorithm.HMAC256(SECRET));
}
public static Map verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
// token 校验失败, 抛出Token验证非法异常
e.printStackTrace();
}
assert jwt != null;
return jwt.getClaims();
}
}
定义拦截器:对需要token验证的接口进行拦截
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lixianhe.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Component
public class JWTInterceptor implements HandlerInterceptor {
@Value("token.jwt.header")
private String header;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map map = new HashMap<>();
// 获取请求头中的token
String token = request.getHeader(header);
if(token ==null){
response.setStatus(401);
return false;
}
try {
// 验证token,返回token中的信息
JwtUtils.verifyToken(token);
return true;
}catch (SignatureVerificationException e){
map.put("msg","无效签名");
} catch (TokenExpiredException e){
map.put("msg","token过期");
}catch (AlgorithmMismatchException e){
map.put("msg","签名算法不一致");
}catch (Exception e){
map.put("msg","token无效");
}
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
配置拦截器:配置对哪些路径拦截,哪些路径放行
import com.lixianhe.interceptors.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/user/*") // 拦截 /user/**
.excludePathPatterns("/user/login"); // 不拦截 /user/login
}
} 


