Fer*_*ina 5 rest restful-authentication spring-mvc spring-security angular
我试图将Spring安全性与自定义角度2登录集成,这是我的应用程序的特定端点受弹簧安全保护,尝试访问它将重定向到/登录,在角度2处理.现在的情况我没有了解如何执行登录并在登录后授予对后端API的访问权限.
我正在配置弹簧安全性如下:
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors().and()
.authorizeRequests()
.antMatchers("/api/someEndpoint/**")
.hasRole(ADMIN_ROLE).and().formLogin()
.loginPage("/login").and().logout();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
Run Code Online (Sandbox Code Playgroud)
因为我有默认登录一切正常,但我发现自己无法创建一个有效的角度2登录集成.我在角度2中尝试了以下代码无效:
login(loginDetails:Object) {
console.log(loginDetails)
const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
const body = JSON.stringify(loginDetails);
console.log(headers);
console.log(body);
return this.http.post(this.loginUrl, body, options)
}
Run Code Online (Sandbox Code Playgroud)
据我所知,用户名和密码变量名称的弹簧安全默认值是"用户名"和"密码",我肯定会在请求体中传递,所以当传递一些无效的用户数据时,{"username":"admin", "password" : "pass"}我应该重定向到/ login?错误或其他什么,并且成功通过身份验证后,我应该重定向到/ welcome并保持身份验证
我有我的数据库中定义的用户和传递,我的自定义userDetailsService检查它是否欢迎任何答案,评论或问题
使用API后,您将使用HTTP Basic或令牌身份验证,而不是Form 1.使用任何一个时都需要使用HTTPS.
要使用Angular 2以HTTP Basic方式进行身份验证,登录服务可能如下所示:
login (loginDetails: any): Observable<LoginResponse> { // custom class, may be empty for now
let headers = new Headers({
'Authorization': 'Basic ' + btoa(loginDetails.login + ':' + loginDetails.pass),
'X-Requested-With': 'XMLHttpRequest' // to suppress 401 browser popup
});
let options = new RequestOptions({
headers: headers
});
return this
.http
.post(this.loginUrl, {}, options)
.catch(e => this.handleError(e); // handle 401 error - bad credentials
}
Run Code Online (Sandbox Code Playgroud)
...然后你可以在一个组件中订阅它:
loginNow() {
this
.loginService
.login(this.loginDetails)
.subscribe(next => {
this.router.navigateByUrl("/"); // login succeed
}, error => {
this.error = "Bad credentials"; // or extract smth from <error> object
});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以loginNow()像这样使用组件模板中的方法(click)="loginNow().
一旦服务器接受授权,JSESSIONID由于Spring Security功能,将自动存储在您的浏览器中,并且您不会每次都被迫发送凭据详细信息以访问私有资源.
您的登录服务器方法可能如下所示:
@PreAuthorize("hasRole('USER')")
@PostMapping("/login")
public ResponseEntity login() {
return new ResponseEntity<>(HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
...... 401 UNAUTHORIZED一旦授权失败,它将拒绝,或者200 SUCCESS如果不授权,它将接受.
如何以适当的方式设置服务器有许多Spring Security演示项目 - https://github.com/spring-guides/tut-spring-security-and-angular-js
代码未经过测试:(