首页 > 解决方案 > 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,但问题仍然存在。

我使用过滤器方法对此进行了跟进,但即使在其余安全配置之前应用过滤器,问题仍然存在。

标签: spring-bootspring-security

解决方案


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.


推荐阅读