我正在用Spring-MVC構建一個Angular2應用程序。我用Spring Security添加了認證,當我用郵遞員查詢我的REST服務器時,一切都很好。當我在我的Angular2頭文件中添加Authorization
時,出現401錯誤。Angular2身份驗證失敗,401
錯誤: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401
我Angular2服務:
@Injectable()
export class BookService {
headers = new Headers();
options = new RequestOptions({ headers: this.headers });
constructor(
private http: Http) {
this.headers.append('Content-Type', 'application/json');
this.headers.append('Authorization', 'Basic ' + btoa('nirgn:password'));
}
getBooksByCategory(categoryId: number) {
return this.http.get(environment.baseUrl + 'categories/' + categoryId + '/books', this.options)
.map((res: Response) => <Book[]>res.json()._embedded.books)
.catch(this.handleError);
}
}
在春天,我讓所有的起源是這樣的:response.addHeader("Access-Control-Allow-Origin", "*");
(在CORSFilter implements Filter
類)。
另外,我補充這樣的認證:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().anyRequest().authenticated();
}
當我刪除.and().authorizeRequests().anyRequest().authenticated()
我不從服務器獲得任何錯誤,並且能夠GET
數據。
因此,總而言之,我很確定它不是Access-Control-Allow-Origin
,這是因爲服務器沒有得到我的授權標頭。當我嘗試在postman中查詢服務器時,沒有auth我也得到401,但是當我添加基本身份驗證時,我得到200.
我還檢查郵遞員和angualr2中的密碼輸出以確保'Basic ' + btoa('nirgn:password')
in angualr2輸出相同的密碼郵差,這是一樣的。這是它: