【发布时间】:2021-02-22 05:20:53
【问题描述】:
从我的 Angular 应用程序到 Spring Boot 后端的跨域请求被 CORS 阻止,仅使用 POST、PUT。允许 GET 并按预期工作。
这是我的配置..
后端:
cors 过滤器 -
@Configuration
public class CORSConfiguration {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedMethods(Arrays.asList("PUT", "POST", "GET", "DELETE", "OPTIONS"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "X-Requested-With", "X-Requested-By",
"Content-Type", "Accept", "Authorization"));
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/*").authenticated().and()
.jee().mappableAuthorities("xxxxxxx");
}
}
ng:
public postIT(payload: Data): Observable<Data> {
return this.http.post<Data>(url, payload) , {
withCredentials: true
});
}
错误:
我在这里遗漏了什么?请告诉我。
【问题讨论】:
-
具体问题是服务器响应 CORS 预检 OPTIONS 请求时出现 401 错误 - 显然是因为它需要对路由甚至 OPTIONS 请求进行身份验证。解决方法是必须更改服务器配置,以便它允许未经身份验证的 OPTIONS 请求,并以 200 OK 响应它们。在stackoverflow.com/a/45406085/441757查看答案
-
对,我已经允许 OPTIONS req 绕过身份验证。通过设置:
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll() -
显然绕过不足以阻止该路由允许未经身份验证的 OPTIONS 请求。否则,您将不会收到对 OPTIONS 请求的 401 响应。 i.stack.imgur.com/9ojsO.jpg 处的图片绝对表明您收到了对 OPTIONS 请求的 401 响应。
标签: angular spring-boot cors preflight