JWT验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Component
public class Authorization implements HandlerInterceptor {
@Autowired
private JwtUtil jwtUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
final String authHeader = request.getHeader("Admin-Token");
try {
if (!StringUtils.isEmpty(authHeader)) {
// System.out.println(authHeader);
Claims claims = jwtUtil.parseJWT(authHeader);
if (!"admin".equals(claims.get("roles"))) {
throw new MyException(50008,"未经授权的访问");
}
} else {
throw new MyException(50008,"未经授权的访问");
}
} catch (Exception e) {
throw new MyException(50008,"未经授权的访问");
}
return true;
}
}

拦截器配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class GatewayConfig implements WebMvcConfigurer {
@Autowired
private Authorization authorization;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorization)
.addPathPatterns("/**")
.excludePathPatterns("/user/login", "/user/registry", "/user/info"
, "/webjars/**", "/swagger-resources/**", "/swagger-ui.html/**"
);
}
}

但是因为浏览器发请求是先发OPTION请求再发对应的业务请求的,而在发OPTION请求的时候是不带请求头的此时JWT效验会直接拒绝前端的连接,这也就导致了前端无法访问后端的业务接口。解决方法是在JWT验证的时候如果发现浏览器发的是OPTION请求就直接放行。

1
2
3
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
return true;
}