【发布时间】:2018-11-12 20:36:04
【问题描述】:
我正在尝试使用 Angular 和 Spring Boot 实现登录功能。
我正在关注春季教程https://spring.io/guides/tutorials/spring-security-and-angular-js/ 但就我而言,我的 Angular 项目托管在 localhost:4200 上,spring 托管在 localhost:8080 上
现在我正在向 Spring 服务器发送一个“/用户”请求。我的角度代码看起来像:
const headers = new HttpHeaders(credentials ? {
authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
this.http.get('http://localhost:8080'+'/user', { headers: headers }).subscribe(response => {
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
return callback && callback();
});
现在由于 CORS,它会发送 OPTIONS 请求,该请求成功,状态为 200。 在此之后,它不会发送实际的 GET 请求,该请求应该将凭据发送为 Angular $http is sending OPTIONS instead of PUT/POST
我的 spring 代码如下所示:
@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders={"x-auth-token", "x-requested-with", "x-xsrf-token"})
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().cors().and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
.anyRequest().authenticated().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
我还在 pom 文件中添加了 Spring Security。
请您帮忙看看为什么 GET 请求在 OPTIONS 请求后没有被触发。
【问题讨论】:
-
你能检查浏览器开发工具(网络标签)
-
我的响应头看起来像:
Access-Control-Allow-Headers: x-requested-with Access-Control-Allow-Methods: GET,HEAD,POST Access-Control-Allow-Origin: * Access-Control-Max-Age: 3600 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Length: 0 Date: Sun, 03 Jun 2018 09:16:14 GMT Expires: 0 Pragma: no-cache Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block -
这是您的 OPTIONS 回复吗??
-
是的,它是我的 OPTIONS 请求的响应标头
-
OPTIONS成功后浏览器是否还有其他调用??
标签: java spring angular spring-boot