Cors过滤器不适用于弹簧靴

时间:2018-04-06 09:02:34

标签: spring-boot cors servlet-filters

我正在使用spring boot过滤器。我已将CORS bean注册为

@Bean
public FilterRegistrationBean simpleCORSFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        SimpleCORSFilter filter = new SimpleCORSFilter();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        config.applyPermitDefaultValues();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Integer.MAX_VALUE);
        bean.setFilter(filter);
        return bean;
    }

我为此编写了一个过滤器类。 虽然这个类正在实例化,但UI的请求在这里失败了。

@Component
public class SimpleCORSFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
            LOGGER.info("start");

                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,auth-token");
                if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
                    response.setStatus(HttpStatus.NO_CONTENT.value());
                }else{
                    AuthenticationRequestWrapper requestAuth = new AuthenticationRequestWrapper((HttpServletRequest) request);
                    filterChain.doFilter(requestAuth, response);
                }
                LOGGER.info("end");
    }
}

但我仍然收到以下错误

cors header ‘access-control-allow-origin’ missing

4 个答案:

答案 0 :(得分:2)

我认为你不需要豆子。在@Order(Ordered.HIGHEST_PRECEDENCE)之后添加@Component可能会解决您的问题。这将告诉spring这个配置应该具有最高优先级。为了保持一致,请使用HttpServletResponse.SC_OK代替HttpStatus.NO_CONTENT.value()

答案 1 :(得分:1)

我建议尝试使用这个https://gist.github.com/keesun/2245179

适合我,然后将其添加到WebMvcConfigurer

public class Interceptors implements WebMvcConfigurer {
  private final CorsInterceptor corsInterceptor;

  @Autowired
  public Interceptors(CorsInterceptor corsInterceptor) {
    this.corsInterceptor = corsInterceptor;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(this.corsInterceptor).addPathPatterns("/**");
  }
}

我还将@Configuration添加到CorsInterceptor

答案 2 :(得分:1)

根据官方Spring Boot文档:

以下是如何使用注释和过滤器配置CORS的示例:

启用CORS

控制器方法CORS配置

为了使RESTful Web服务在其响应中包含CORS访问控制头,您只需要在处理程序方法中添加@CrossOrigin注释:

src/main/java/hello/GreetingController.java
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
    System.out.println("==== in greeting ====");
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

全球CORS配置

作为细粒度基于注释的配置的替代方法,您还可以定义一些全局CORS配置。这与使用基于Filter的解决方案类似,但可以在Spring MVC中声明,并与细粒度@CrossOrigin配置相结合。默认情况下,允许使用所有来源和GETHEADPOST方法。

src/main/java/hello/GreetingController.java
@GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required=false, defaultValue="World") String name) {
    System.out.println("==== in greeting ====");
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
src/main/java/hello/Application.java
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

答案 3 :(得分:0)

我有同样的问题。我以为我的spring cors配置错误,但是我意识到该请求必须满足一些要求:

方法必须为OPTIONS
Origin标头的存在
Access-Control-Allow-Methods标头的存在

我发现here

尝试一下:

1-只需将@CrossOrigin批注添加到您的控制器中
2-使用OPTIONS方法使用这2个标头发送您的请求:
访问控制请求方法:GET
来源:*

您应该获得Access-Control-Allow-Origin:*

Juani