我正在使用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);
}