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サービス:response.addHeader("Access-Control-Allow-Origin", "*");
(CORSFilter implements Filter
クラス):春
@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);
}
}
私はこのように、すべての起源を可能にします。
また、私はこのような認証を追加しました:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().anyRequest().authenticated();
}
を私は.and().authorizeRequests().anyRequest().authenticated()
を削除するとき、私は、サーバーからGET
にデータを任意の誤り、およびことを得ることはありません。
したがって、私は確かにそれがAccess-Control-Allow-Origin
ではないと確信しています、そして、それはサーバが私の認証ヘッダーを得ないからです。私は郵便配達員でサーバーを照会しようとすると、401も得られますが、基本認証を追加すると200になります。
郵便配達員と救助者のパスワードの出力を確認してください。'Basic ' + btoa('nirgn:password')
angualr2郵便番号と同じパスワードを出力し、それは同じです。ここにあります: