2016-07-07 248 views
2

我使用spring安全性与OAuth2(版本:4.0.4.RELEASE)和spring(verison:4.3.1.RELEASE)。Spring Security CORS过滤器不起作用

我正在开发Angular的前端,我正在使用grunt connect:dev(http://127.0.0.1:9000)。当我试图登录本地主机地址一切工作正常,但其他我收到提示:

“的XMLHttpRequest无法加载http://localhost:8084/oauth/token?client_id=MY_CLIENT_ID回应预检要求未通过访问控制检查:没有“访问控制 - 允许 - Origin'标题出现在请求的资源上,因此Origin'http://127.0.0.1:9000'不允许访问,响应的HTTP状态码为401.“

我在WebMvcConfigurerAdapter(如下)中配置了映射(覆盖public void addCorsMappings(CorsRegistry注册表)),但它仍然不适用于http://127.0.0.1:9000

registry.addMapping("/**") 
      .allowedOrigins("http://127.0.0.1:9000") 
      .allowedMethods("POST", "OPTIONS", "GET", "DELETE", "PUT") 
      .allowedHeaders("X-Requested-With,Origin,Content-Type,Accept,Authorization") 
      .allowCredentials(true).maxAge(3600); 

配置基于:https://spring.io/guides/gs/rest-service-cors/

请点我正确的directon来解决这个问题。

+0

如果我理解正确,您尝试从不同的ip 127.0.0.1访问。 (你不在本地主机了)。但你只允许从本地主机访问(127.0.0.1) –

+0

可能的重复[Spring CORS否'访问控制 - 允许来源'头部存在](http://stackoverflow.com/questions/35091524/spring-cors -no-access-control-allow-origin-header-is-present) –

+0

Periklis - 是的,我试图从不同的IP访问。我只允许从http:// localhost:8084 /访问。 – Matt

回答

0

你可以尝试这样的事情

@Configuration 
public class CorsConfig { 
    @Bean 
    public WebMvcConfigurer corsConfigurer() { 
     return new WebMvcConfigurerAdapter() { 
      @Override 
      public void addCorsMappings(CorsRegistry registry) { 
      registry.addMapping("/**") 
        .allowedMethods(HttpMethod.OPTIONS.name(), 
          HttpMethod.PATCH.name(), 
          HttpMethod.PUT.name(), 
          HttpMethod.DELETE.name(), 
          HttpMethod.GET.name(), 
          HttpMethod.POST.name()) 
        .maxAge(360); 
      } 
     }; 
    } 
} 

注:Spring版本应该是4.2或更高版本

+0

不幸的是仍然没有工作:( – Matt

+0

你可以尝试添加:'.allowedHeaders(“header1”,“header2”)',接受发送到服务器的头部变量。 – NguaCon

6

希望你找到了答案前不久,但是如果没有(如果任何人发现这个问题,因为我搜索):

问题是,春季安全使用过滤器和这些过滤器通常优先于用户定义的过滤器,@CrossOrigin和类似的注释离子等。

对我而言,有效的方法是将CORS过滤器定义为具有最高优先级的bean,如建议here

@Configuration 
public class MyConfiguration { 

    @Bean 
    public FilterRegistrationBean corsFilter() { 
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     CorsConfiguration config = new CorsConfiguration(); 
     config.setAllowCredentials(true); 
     config.addAllowedOrigin("http://127.0.0.1:9000"); 
     config.setAllowedMethods(Arrays.asList("POST", "OPTIONS", "GET", "DELETE", "PUT")); 
     config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization")); 
     source.registerCorsConfiguration("/**", config); 
     FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
     bean.setOrder(Ordered.HIGHEST_PRECEDENCE); 
     return bean; 
    } 
}