2

我有一个REST后端和Spring(启用CORS的Apache Tomcat 7上运行)和一个AngularJS客户端。两者都运行在不同的领域(就CORS而言)。跨域HTTP请求在AngularJS中失败

我试图实现基本身份验证,但它只适用于客户端和服务都在相同的主机/端口号,即使我证实CORS在服务器端正常工作。 (我通过禁用basic auth impl来测试它,并简单地检查客户端是否能够从服务中获取数据。只要服务上的CORS过滤器正常工作,它就会工作 - 正如预期的那样)。

下面是客户端配置

启用对角跨域请求(我听说,这是没有必要的对角1.2+但它似乎没有工作无论哪种方式)

myApp.config(['$httpProvider', function ($httpProvider) { 
    $httpProvider.defaults.useXDomain = true; 
    delete $httpProvider.defaults.headers.common['X-Requested-With']; 
}]); 

HTTP调用

$http({method: 'GET', url: url + userId, headers: {'Authorization': 'Basic ' + Base64.encode('admin' + ':' + 'password')}}). 
    success(function(data, status, headers, config) { 
// 
    }). 
    error(function(data, status, headers, config) { 
// 
    }); 

后端CORS过滤

FilterRegistration corsFilter = container.addFilter("CORS", CORSFilter.class); 
corsFilter.setInitParameter("cors.supportedMethods", "GET, HEAD, POST, PUT, DELETE, OPTIONS"); 
corsFilter.setInitParameter("cors.supportedHeaders", "Accept, Origin, X-Requested-With, Content-Type, Last-Modified"); 
corsFilter.setInitParameter("cors.supportsCredentials ", "false"); 
corsFilter.setInitParameter("cors.allowOrigin ", "*"); 
corsFilter.addMappingForUrlPatterns(null, false, "/*"); 

Spring Security进行基本验证

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .inMemoryAuthentication() 
       .withUser("admin").password("password").roles("USER", "ADMIN"); 
    } 


    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests() 
     .antMatchers("/**").hasRole("USER") 
     .anyRequest().anonymous() 
     .and() 
     .httpBasic(); 
    }  
} 

错误,我得到(全误差,为每个请求由客户支付给提供服务的另一个域运行时)

Failed to load resource: the server responded with a status of 403 (Forbidden) (11:53:44:206 | error, network) 
    at http://localhost:8081/myApp-service/user/6 
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (11:53:44:209 | error, network) 
    at http://localhost:8081/myApp-service/user/6 
XMLHttpRequest cannot load http://localhost:8081/myApp-service/user/6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (11:53:44:211 | error, javascript) 
    at app/index.html 

Chrome的请求头

Request URL:http://localhost:8081/myApp-service/user/6 
Request Method:OPTIONS 
Status Code:403 Forbidden 
Request Headersview source 
Accept:*/* 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-US,en;q=0.8 
Access-Control-Request-Headers:accept, authorization 
Access-Control-Request-Method:GET 
Connection:keep-alive 
Host:localhost:8081 
Origin:http://localhost:8383 
Referer:http://localhost:8383/myApp-client/app/index.html 
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36 
Response Headersview source 
Content-Length:93 
Content-Type:text/plain;charset=ISO-8859-1 
Date:Wed, 26 Feb 2014 18:55:00 GMT 
Server:Apache-Coyote/1.1 

因此,大家可以看到,角是无法应对CORS飞行前OPTIONS甚至AFTE适当CON无花果写。一切工作正常在同一个域和后端CORS过滤器被测试独立工作。所以不知道我在这里错过了什么。谢谢!

+1

问题出在您的服务器代码,而不是Angular。您可以通过查看服务器未正确处理OPTIONS /预检的响应来查看。 –

+0

@RayNicholus这听起来很合理。到目前为止,我只怀疑客户。由于我的CORS过滤器已经接受了“选项”,所以我想不出任何其他可以让后端工作的变化。有任何想法吗? – user6123723

+0

看起来你的服务器正在返回一个403的状态码。你可能想知道为什么它会这样做。 –

回答

3

我认为问题出在我的客户身上,但正如Ray指出的那样,这是我的服务。

当我知道我需要调试我的服务时,我下载了CORSFilter的源代码,正确放置了断点来研究服务器响应。

这样做,我发现CORS过滤器在请求标题中遇到“授权”时会抛出异常。这是因为我没有将它添加到支持的标题列表中。在我将它添加到列表后,问题很快得到解决。

corsFilter.setInitParameter("cors.supportedHeaders", "Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization"); 
+0

你把这个和平代码放在哪里?我与我的spring security + angularjs应用程序有同样的问题... – skywalker

+0

@NevyanovL http://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter – user6123723