我正在做一个Spring Boot 2+ Angular 5项目。对于那些想要重新认识它的人来说,这是从Spring Guides站点上的Spring Security and Angular tutorial获得的超级灵感。
我有一个使用基本身份验证的安全后端。
@SpringBootApplication
@RestController
public class BasicApplication extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(BasicApplication.class, args);
}
@GetMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello Spring Security Boot 2 and Angular");
return model;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/resource")
.allowedOrigins("http://localhost:4200")
.allowedMethods("GET");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
当卷曲/resource
端点时,I do成功
curl http://user:password@localhost:8080/resource
我想使用Angular执行完全相同的身份验证。因此,我实现了以下组件:
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Hello WAT';
greeting = { id: 'XXX', content: 'Hello World' };
constructor(private http: HttpClient) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'user:password'
})
};
http
.get<any>('http://localhost:8080/resource', httpOptions)
.subscribe(resource => (this.greeting = resource));
}
}
以下是我在浏览器日志中的记录:
Access-Control-Request-Headers authorization,content-type
从逻辑上讲,下面是Spring Sec调试日志所说的:
2018-07-16 14:25:28.355 DEBUG 8792 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9a00c039: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
...
2018-07-16 14:25:28.377 DEBUG 8792 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
发布于 2018-07-17 06:06:51
首先,我必须感谢user184994的有用评论:添加'Basic ' + btoa(...)
确实很有用!
'Authorization': 'Basic ' + btoa('user:password')
接下来,在使用各种浏览器进行测试后,我最终发现了以下错误消息:
Failed to load http://localhost:8080/resource: Response for preflight has invalid HTTP status code 401.
经过一些研究和努力,我发现在Spring Security中添加CORS配置确实起到了作用。
http
...
.and()
.cors()
https://stackoverflow.com/questions/51361973
复制相似问题