public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/* MethodHandle methodHandle = handler instanceof MethodHandle ? ((MethodHandle) handler) : null;
if(methodHandle == null){
return true;
}*/
String token = request.getHeader("token");
DecodedJWT decode = JWT.decode(token);
Claim name = decode.getClaim("name");
System.out.println("TokenInterceptor name:"+name.as(String.class));
boolean abc = JwtUtil.verify(token, "abc");
System.out.println("TokenInterceptor abc:"+abc);
return abc;
}
}
//implements WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePath = new ArrayList<>();
excludePath.add("/channel/login");
//登录
registry.addInterceptor(tokenInterceptor)
.excludePathPatterns(excludePath)
.addPathPatterns("/**");
//除了登陆接口其他所有接口都需要token验证
WebMvcConfigurer.super.addInterceptors(registry);
}
public class JwtUtil {
public static String getToken(User user){
Map header = new HashMap<>();
header.put("Content-Type","application/json");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,60);
String token = JWT.create()
.withHeader(header)
.withClaim("name", user.getName())
.withExpiresAt(calendar.getTime())
.sign(Algorithm.HMAC256(user.getPass()));
System.out.println("JwtUtil getToken token:"+token);
return token;
}
public static boolean verify(String token,String pass){
try {
JWTVerifier require = JWT.require(Algorithm.HMAC256(pass)).build();
DecodedJWT verify = require.verify(token);
System.out.println("JwtUtil verify verify:"+verify);
return true;
}catch (Exception e){
return false;
}
}
}
@ResponseBody
@RequestMapping("/login")
public String login(@RequestBody User user){
//默认用户登录成功
//生成token
String token = JwtUtil.getToken(user);
user.setToken(token);
return token;
}
标签:return,String,verify,jwt,token,user,public
From: https://www.cnblogs.com/leifonlyone/p/18391400