[英]angular 2 login with spring security
我正在嘗試將 spring 安全性與自定義 angular 2 登錄集成,這是我的應用程序的特定端點受到 spring 安全性的保護,嘗試訪問它將重定向到在 angular 2 中處理的 /login。就目前情況而言,我沒有關於如何執行登錄並在登錄后授予對后端 API 的訪問權限的線索。
我正在配置 spring 安全性如下:
@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);
}
因為我有默認登錄,所以一切正常,但我發現自己無法創建有效的 angular 2 登錄集成。 我在angular 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)
}
據我所知 spring 用戶名和密碼變量名稱的安全默認值是“用戶名”和“密碼”,我確信它們是在請求正文中傳遞的,因此在傳遞一些無效的用戶數據時,如{"username":"admin", "password": "pass"}
我應該被重定向到 /login?error 什么的,當成功通過身份驗證時,我應該被重定向到 /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
}
...然后你可以在一個組件中訂閱它:
loginNow() {
this
.loginService
.login(this.loginDetails)
.subscribe(next => {
this.router.navigateByUrl("/"); // login succeed
}, error => {
this.error = "Bad credentials"; // or extract smth from <error> object
});
}
然后你可以在組件模板中使用loginNow()
方法,如下所示(click)="loginNow()
。
一旦服務器接受授權,由於Spring Security功能, JSESSIONID
將自動存儲在您的瀏覽器中,並且您不會每次都被迫發送憑據詳細信息以訪問私有資源。
您的登錄服務器方法可能如下所示:
@PreAuthorize("hasRole('USER')")
@PostMapping("/login")
public ResponseEntity login() {
return new ResponseEntity<>(HttpStatus.OK);
}
......一旦授權失敗,它將以401 UNAUTHORIZED
拒絕,如果不能,則接受200 SUCCESS
。
如何以適當的方式設置服務器有許多Spring Security演示項目 - https://github.com/spring-guides/tut-spring-security-and-angular-js
代碼未經過測試:(
您的spring security配置需要如下所示
http!!
.cors().and()
.csrf().disable()
.authorizeRequests()
.requestMatchers(object: RequestMatcher {
override fun matches(request: HttpServletRequest?): Boolean {
return CorsUtils.isCorsRequest(request)
}
}).permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin().permitAll()
我有一個類似的問題,但我不得不重寫此處提到的成功注銷處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.