【问题标题】:Spring Boot CORS issueSpring Boot CORS 问题
【发布时间】:2021-04-11 09:31:51
【问题描述】:

我正在尝试通过本教程学习弹簧:

https://spring.io/guides/tutorials/react-and-spring-data-rest/

但我将前端应用程序作为一个单独的应用程序。 调用时:http://localhost:8080/api/employees

如何全局启用 CORS?谢谢!

在应用程序中尝试过:

@Bean
    public WebMvcConfigurer configurer()
    {
        return new WebMvcConfigurer()
        {
            @Override
            public void addCorsMappings(CorsRegistry registry)
            {
                registry.addMapping("/api/*").allowedOrigins("http://localhost:8000");
            }
        };
    }

但没用

使用自定义 @RestController 进行了一些测试,如下所示:

https://spring.io/guides/gs/rest-service-cors/#global-cors-configuration 并从外部前端应用程序调用 http://localhost:8080/api/greeting 工作正常,只有那些通过 spring 自动生成的其余端点 CRUD 不允许 CORS 存在.. 如何避免这个问题?

【问题讨论】:

  • 没有得到您的问题? from external frontend app works fine, only those rest endpoints CRUD auto generated via spring are not allowed CORS there.. How to avoid this issue ?

标签: spring-boot


【解决方案1】:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }
}

【讨论】:

    【解决方案2】:

    添加:

    import org.springframework.stereotype.Component;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * Note this is a very simple CORS filter that is wide open.
     * This would need to be locked down.
     * Source: https://stackoverflow.com/questions/39565438/no-access-control-allow-origin-error-with-spring-restful-hosted-in-pivotal-web
     */
    @Component
    public class CORSFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            chain.doFilter(req, res);
        }
    
        public void init(FilterConfig filterConfig) {}
    
        public void destroy() {}
    
    }
    

    帮助

    【讨论】:

      【解决方案3】:

      尝试将其添加到您的主应用程序类文件中:

          @Bean
      public FilterRegistrationBean corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin("*");
          config.addAllowedHeader("*");
          config.addAllowedMethod("*");
          source.registerCorsConfiguration("/**", config);
          FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
          bean.setOrder(0);
          return bean;
      }
      

      【讨论】:

      • "java.lang.IllegalArgumentException: 当 allowCredentials 为 true 时,allowedOrigins 不能包含特殊值 "*",因为它不能在 "Access-Control-Allow-Origin" 响应标头上设置。要允许一组来源的凭据,明确列出它们或考虑改用“allowedOriginPatterns”。“
      • 这个答案在 Spring Boot 的最后一个版本之前是正确的。从现在开始,您不能使用设置为 true 的允许凭据和带通配符的允许来源。请看stackoverflow.com/questions/66060750/…
      • addAllowedOriginPattern("*") 为我工作。
      猜你喜欢
      • 2016-07-09
      • 2018-07-12
      • 1970-01-01
      • 2020-09-08
      • 2019-05-17
      • 2017-09-09
      • 2017-04-13
      • 2018-10-30
      相关资源
      最近更新 更多