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));
}


本文介绍了如何在Java应用中使用JWT(JSON Web Tokens)进行认证,并通过自定义拦截器处理权限验证。首先引入了com.auth0的java-jwt库,然后配置了WebMvcConfig以添加拦截器,拦截所有请求并排除登录路径。接着展示了AuthenticationInterceptor类的实现,该类检查请求头中的token,如果token无效或过期,会返回相应的错误信息。在配置过程中遇到了bean定义冲突的问题,通过设置`allow-bean-definition-overriding`为true解决了问题。最后提供了一个登录接口示例,用于获取JWT token。
21万+

被折叠的 条评论
为什么被折叠?



