/**
jwt 后台访问拦截 拦截器配置文件 config
/
@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 默认拦截所有路径
registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
}
@Bean
public JwtAuthenticationInterceptor authenticationInterceptor() {
//这里报错 提示找不到源
return new JwtAuthenticationInterceptor();
}
}
/** 自定义拦截**/
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object object) throws Exception {
// 从请求头中取出 token 这里需要和前端约定好把jwt放到请求头一个叫token的地方
String token = httpServletRequest.getHeader("token");
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
// 检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
// 默认全部检查
else {
System.out.println("被jwt拦截需要验证");
// 执行认证
if (token == null) {
// 未登录非法操作
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user Name
String userId = JwtUtils.getAudience(token);
if (userId == null) {
// 未登录非法操作
throw new RuntimeException("无token,请重新登录");
}
// 获取载荷内容
String userName = JwtUtils.getClaimByName(token, "userName").asString();
String realName = JwtUtils.getClaimByName(token, "realName").asString();
// 放入attribute以便后面调用
httpServletRequest.setAttribute("userName", userName);
httpServletRequest.setAttribute("realName", realName);
return true;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
你确定只有这些?