1.导入jwt依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency>
2.配置拦截
/** * WebMvcConfig配置 */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/user/login"); } @Bean public AuthenticationInterceptor authenticationInterceptor() { //拦截器 return new AuthenticationInterceptor(); } }
3.自定义拦截器
@Component public class AuthenticationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("token"); HashMap<String, Object> map = new HashMap<>(); try { JwtUtils.verifyToken(token); return true; } catch (SignatureVerificationException e) { e.printStackTrace(); map.put("msg","无效的签名"); }catch (TokenExpiredException e){ e.printStackTrace(); map.put("msg","该令牌已过期"); }catch (AlgorithmMismatchException e){ e.printStackTrace(); map.put("msg","算法不匹配"); }catch (Exception e){ e.printStackTrace(); map.put("msg","token无效!"); } map.put("status",false); String errorMsg = JSONObject.toJSONString(map); response.setContentType("application/json; charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.print(errorMsg); writer.close(); return false; } }
4.添加@component是会报The bean ‘xxx’, defined in class path resource [com/uniedu/frame/swagger2/Swagger2Configuration.class], could not be registered. A bean with that name has already been defined in class path resource
5.解决方法
main: allow-bean-definition-overriding: true
6.测试
@PostMapping("/login") @ResponseBody private Msg getToken(@RequestBody Msg msg){ HashMap<String, String> claim = new HashMap<>(); claim.put("id","PVor7HsCjhtwmmrewNrXh9UeO2zy4pWZ"); claim.put("username","住户1"); return new Msg().success(JwtUtils.getToken(claim)); }