spring-boot - Spring Security Cors 启用
问题描述
我尝试在 SpringBoot 应用程序中添加一个简单的 CorsRegistry。我使用选项 1 在Spring Boot Security CORS问题中遵循了Gilbert Arenas Dagger的答案。但是,在尝试使用 React 到达我的后端时,我仍然会生成一个 CORS 错误。使用 Postman,一切都按预期工作,所以我知道我的配置中一定有一些遗漏,我似乎无法找到它。
我的安全配置文件:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http .cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers("/iotd").hasRole("USER")
.anyRequest().authenticated();
}
}
我的 CorsConfig 文件
@Configuration
public class CorsConfig {
private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("CORS implemented");
registry.addMapping("/**")
.allowedMethods("GET", "POST")
.allowedHeaders("*")
.allowedOrigins("*");
}
};
}
}
启动后,记录器被触发并表示 CORS 注册表已实现。
然后我确实按照他的回答中的第二个选项,使用 CorsConfigurationBean,但问题仍然存在。
我使用过滤器方法对此进行了跟进,但即使在其余安全配置之前应用过滤器,问题仍然存在。
解决方案
Add OPTIONS
method in allowedMethods which is sent by browser for security purpose.
This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.
推荐阅读
- javascript - 音频播放减慢游戏速度
- python - 将按钮重置为原始文本pyqt5
- python - 如何使用 pyspark 数据框读取固定字段文件并将其插入数据库?
- unit-testing - 如何存根方法的回调?
- github-api - Github 应用程序不会重定向到 Github Enterprise 中的回调 url
- regex - 替换 HEX 文件的最后一次出现 - Perl Regex
- html - Vue href 与静态 url 绑定
- databricks - 在 Azure Purview 中扫描 Delta 表时未创建沿袭
- apache-poi - POI的多级和主要组之间的行重叠无效
- angular - 如何使用 API 获得预先输入的建议