public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
boolean result = true;
String resultString = "";
// TokenResult tokenResult = JwtUtils.parseToken(token);
// 重置时间
// redisTemplate.opsForValue().set(RedisPrefixuUils.getKey(""), token);
TokenResult tokenResult = JwtUtils.checkToken(token);
if (tokenResult == null) {
result=false;
resultString="access token invalid";
}else {
String phone = tokenResult.getPhone();
String identity = tokenResult.getIdentity();
String tokenKey = RedisPrefixuUils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
String tokenRedis = redisTemplate.opsForValue().get(tokenKey);
if (StringUtils.isEmpty(tokenRedis)||!StringUtils.equalsIgnoreCase(token.trim(),tokenRedis.trim())){
result=false;
resultString="access token invalid";
}
}
if (!result) {
PrintWriter writer = response.getWriter();
writer.println(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
}
return result;
}
}
对应的配置文件编写
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public JwtInterceptor jwtInterceptor(){
return new JwtInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")//拦截的路径
.excludePathPatterns("/noauthTest")//不拦截的路径
.excludePathPatterns("/verification-code")//不拦截的路径
;
}
}
JWT工具类
public class JwtUtils {
//salt 盐
public static final String SIGN = "CPFyuyang!@#$$";
//生成token
public static String generatorateToken(Map<String, String>map){
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k,v);
});
//token时间设定
Calendar instance = Calendar.getInstance();
instance.add(Calendar.MINUTE,30);
Date time = instance.getTime();
builder.withExpiresAt(time);
//生成token
String sign = builder.sign(Algorithm.HMAC256(SIGN));
return sign;
}
//解析token
public static Map<String, Claim> parseToken(String token){
DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
String age = jwt.getClaim("age").asString(); //主题内容
System.out.println("age = " + age);
System.out.println("jwt.getToken() = " + jwt.getToken());
System.out.println("jwt.getHeader() = " + jwt.getHeader());
Map<String, Claim> claims = jwt.getClaims();
System.out.println("claims = " + claims);
return claims;
}
/**
* 校验token
* @param token
* @return
*/
public static TokenResult checkToken(String token){
try {
TokenResult tokenResult = JwtUtils.parseToken(token);
return tokenResult;
} catch (Exception e) {
return null;
}
}
}