package com.pfxt.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
public class JWTUtils {
private static final String SING="!@$^%Q*#REE451#%:>$$@$";
public static String getToken(Map<String, String> map){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,14);
JWTCreator.Builder builder= JWT.create();
map.forEach((k,v)->{
builder.withClaim(k, v);
});
String token = builder.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256(SING));
return token;
}
public static DecodedJWT verify(String token){
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}
}
拦截器
package com.pfxt.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pfxt.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map<String,Object> map=new HashMap<>();
String token =request.getHeader("token");
try {
DecodedJWT verify = JWTUtils.verify(token);
return true;
}catch (SignatureVerificationException e){
e.printStackTrace();
map.put("code",508);
map.put("msg","无效签名");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("code",506);
map.put("msg","token过期");
}catch (AlgorithmMismatchException e){
e.printStackTrace();
map.put("code",507);
map.put("msg","token解析算法不同");
}catch (Exception e){
e.printStackTrace();
map.put("code",505);
map.put("msg","token无效或者未检测到token,请登录获取");
}
String json =new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}