Spring (CORS가 Apache Tomcat 7에서 실행 됨) 및 AngularJS 클라이언트가있는 REST 백엔드가 있습니다. 둘 다 다른 도메인에서 실행됩니다 (CORS에 관한 한).AngularJS에서 도메인 간 HTTP 요청이 실패합니다.
기본 인증을 구현하려고하지만 CORS가 서버 측에서 정상적으로 작동하는지 확인한 후에도 클라이언트와 서비스가 동일한 호스트/포트 번호에있는 경우에만 작동합니다. (필자는 기본 auth impl을 비활성화하고 클라이언트가 서비스에서 데이터를 가져올 수 있는지 단순히 확인하여 테스트했습니다. 예상대로 서비스의 CORS 필터가 작동하는 한 작동합니다.) 여기
는 각도에 대한 크로스 도메인 요청을 사용하여 클라이언트 구성(I 그것이 각도 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, "/*");
봄 보안에 대한 기본 인증
@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();
}
}
오류 I 수 (전체 오류 다른 도메인에서 실행되는 동안 서비스에 클라이언트에 의해 요청에 따라있는 그대로)
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
크롬 요청 헤더
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는 비행 전 옵션을 처리 할 수 없습니다. 무화과는 쓴다. 모든 것이 동일한 도메인에서 잘 작동하며 백엔드의 CORS 필터는 독립적으로 작동하도록 테스트됩니다. 그래서 내가 여기에서 무엇을 놓치고 있는지 확실하지 않습니다. 감사!
문제는 서버 코드와 관련이 있습니다. 각도는 아닙니다. 서버가 OPTIONS/프리 플라이트를 제대로 처리하지 못한다는 응답을 보면 알 수 있습니다. –
@RayNicholus 실제로 합리적이라고 생각합니다. 나는 지금까지 클라이언트를 의심했다. 내 CORS 필터는 이미 "OPTIONS"를 받아들이므로 백엔드를 작동시키기 위해 할 수있는 다른 변화는 생각할 수 없습니다. 어떤 아이디어? – user6123723
귀하의 서버가 403 상태 코드를 반환하는 것처럼 보입니다. 왜 그렇게하고 있는지 파악하고 싶을 것입니다. –