问题
来自浏览器的 CORS OPTIONS 请求正在进入我的 JWT 验证过滤器,并在每个请求上返回 401。我希望在进入 JWT 验证过滤器之前处理 CORS OPTIONS 请求。
背景
在我的 Spring Boot 应用程序中,我创建了一个 JWT 过滤器(它实现 Filter)来拦截每个请求。过滤器的唯一工作是验证 token ,并在 token 过期、签名错误或声明不正确时生成 401,如果 token 有效,则将请求转发到链中的下一个过滤器。
@Component
@Order(1)
public class JweFilter implements Filter {
@Override
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Validate Token and return 401 if invalid
chain.doFilter(request, response);
}
}
我通过扩展 WebMvcConfigurer 启用了 CORS——这似乎是现代方法。
@Configuration
@EnableWebMvc
class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*");
}
}
有谁知道我为什么会遇到这种行为以及如何解决它?
提前感谢任何有信息的人:)
最佳答案
为了解决这个问题,我摆脱了 WebMvcConfigurer 并将其替换为 FilterRegistrationBean https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#filter-based-cors-support
@Configuration
public class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
使用此代码后,CORS 预检请求将在命中 JWT 验证过滤器之前由 FilterRegistrationBean 处理。
关于java - Spring Boot 中的自定义 JWE 过滤器阻止 CORS 选项请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60858730/