Spring Boot 中的 CORS 与 Spring Security + React

Posted

技术标签:

【中文标题】Spring Boot 中的 CORS 与 Spring Security + React【英文标题】:CORS in Spring Boot with Spring Security + React 【发布时间】:2021-10-30 06:05:19 【问题描述】:

部署后,我遇到了 CORS 问题。我可以直接从我的 API 访问数据,但是在尝试从 React 应用程序中获取数据时,我遇到了图像中的问题:

我尝试添加过滤器以添加到每个标题 Access-Control-Allow-Origin 中,它现在从 API 返回数据,我可以在浏览器控制台中看到它,但反应无法获取它

WebSecurity.java

@Override
protected void configure(HttpSecurity http) throws Exception 

    http.cors().and().csrf().disable();

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();

    http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and();

    http.authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);



@Bean
public FilterRegistrationBean crosFilterRegistration()
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(new MyCorsFilter());
    registrationBean.setName("CORS Filter");
    registrationBean.addUrlPatterns("/*");
    registrationBean.setOrder(1);
    return registrationBean;


@Bean
CorsConfigurationSource corsConfigurationSource() 
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("https://*************"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Access-Control-Allow-Origin",
            "Access-Control-Request-Method", "Access-Control-Request-Headers", "Origin",
            "Cache-Control", "Content-Type"));
    configuration.setAllowCredentials(true);

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;

MyCorseFiltre.java

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsFilter implements Filter 

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException 
        final HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "https://**************");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) 
            response.setStatus(HttpServletResponse.SC_OK);
         else 
            chain.doFilter(req, res);
        
    

    @Override
    public void destroy() 
    

    @Override
    public void init(FilterConfig config) throws ServletException 
    

Application.java

@Bean
public WebMvcConfigurer corsConfigurer() 
    return new WebMvcConfigurer() 
        @Override
        public void addCorsMappings(CorsRegistry registry) 
            registry.addMapping("/**").allowedOrigins("https://*************");
        
    ;

【问题讨论】:

【参考方案1】:

这一行

response.setHeader("Access-Control-Allow-Origin", "https://**************");

添加重复的标题。这一行也是如此:

configuration.setAllowedOrigins(Collections.singletonList("https://*************"));

其中一个就足够了。最好是后者。您拥有的大多数 CORS 配置也是如此。

【讨论】:

感谢您的回复,我确实评论了除最后一个以外的所有过滤器,但仍然得到重复的标题。什么会导致这样的问题?

以上是关于Spring Boot 中的 CORS 与 Spring Security + React的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 和安全性中的 CORS 支持

CORS与Spring Boot 2 [重复]

如何使用 Angular 消除 Spring Boot 中的 CORS 错误? [复制]

Kotlin 和 Spring Boot 中的 CORS 预检错误

Spring Boot CORS支持

如何处理 Spring Boot、AngularJS 应用程序中的 CORS 错误?