【发布时间】:2021-04-07 09:37:46
【问题描述】:
我正在使用带有 Angular 9 前端的 Spring Boot 2.2.5 应用程序。
我一直在尝试在 Spring Boot 后端配置一个 CORS 过滤器,以允许任何来源的任何请求的任何标头。
根据我的研究,我目前在我的主要 Application.java 文件中实现的内容应该可以工作:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
但是,我所经历的是,这只允许我从前端到后端的控制器执行GET 调用。对POST 或PUT 的任何其他调用都会失败并出现以下错误:
Access to XMLHttpRequest at 'http://localhost:8080/spring-boot-starter-seed/default-theme/save/cyan' from origin 'http://localhost:8083' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我知道我走在了正确的轨道上,因为如果我删除了我实现的@Bean,那么从前端到后端的所有调用都会由于该错误而失败。但是在实现该 Bean 时,由于某种原因,它仅适用于 GET 请求。
有什么我遗漏的吗?
***** 更新 *****
我不知道这是否会有所帮助,但是,我正在使用 Azure AD 对此应用程序进行身份验证。我有一个看起来像这样的WebSecurityConfig:
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/actuator/**", "/heartbeat/**", "/register", "/unregister").permitAll()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(this.jwtAuthenticationConverter());
}
}
在我之前的帖子中,我说过 GET 请求有效,但这似乎有些错误。
GET /heartbeat 有效。不过……
GET /default-theme 不起作用并失败并出现同样的 No Access-Control-Allow-Origin 错误。
这两个Controller路径的唯一区别是/default-theme不包含在排除的antMatchers中,它受到@PreAuthorize(value = "hasRole('ROLE_access')")的保护
【问题讨论】:
标签: java angular spring spring-boot cors