java - 使用 WebSecurity.ignoring() 时如何修复 CORS
问题描述
我正在使用 Spring 构建一个平台,并通过 JWT 授权。在网关服务中,我有用于解析令牌的自定义过滤器(基于 BasicAuthenticationFilter),但它应该只为安全配置中标记的路由调用,.authenticated()
因此任何人都可以访问的路由被添加到WebSecurity.ignoring()
.
问题是添加路径以WebSecurity.ignoring()
同时禁用 CORS 配置并且OPTIONS
请求不返回Access-Control-*
标头。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// Auth service
.antMatchers("/auth/login", "/auth/renew")
.permitAll()
.antMatchers("/auth/logout", "/auth/session/**")
.authenticated()
// User service
.antMatchers(HttpMethod.POST, "/user/")
.permitAll()
.antMatchers( "/user/confirm/**", "/user/recover", "/user/validate/**")
.permitAll()
.antMatchers("/user/", "/user/change/**")
.authenticated()
// further part of routes...
http
.formLogin()
.disable()
.logout()
.disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtKey));
http.csrf().disable();
http.cors();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Auth service
.antMatchers("/auth/login", "/auth/renew")
// User service
.antMatchers(HttpMethod.POST, "/user/")
.antMatchers( "/user/confirm/**", "/user/recover", "/user/validate/**")
// further part of routes...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(corsOrigins);
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedHeaders(Collections.singletonList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
有没有办法绕过某些路径的特定过滤器?
-解决了-
我已经通过启用WebMvc
和添加 cors 配置解决了我的问题(以前可能会被删除)。
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
解决方案
推荐阅读
- ndepend - 为 NDepend 创建自定义扩展
- javascript - 如何找到函数所在的文件名?
- visual-studio-code - 如何在 Visual Studio Code 中使用 gltf 动画扩展?
- jquery - Jquery标头加载不显示菜单
- php - 在codeigniter库函数中如何调用同一个库的另一个函数
- java - 静态变量与静态方法和静态类有什么区别?
- asp.net-core - 如何在主/从 redis 设置上负载平衡读取?
- mysql - Mysql 2 表一查询
- java - 使用 system.out 从循环 JAVA 内的数组中输出数据
- python - 根据条件查找日期和前后班次