1

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郵便番号と同じパスワードを出力し、それは同じです。ここにあります: enter image description here

答えて

1

私はそれを把握することができます。結局、CORSだった(春)。

IはI(角度で)私は

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated() 
     .and().addFilterAfter(new CORSFilter(), CsrfFilter.class); 
} 

郵便配達でそれが成功した理由は、私はまだ理解していない奇妙なことがあるように作成CORSFilter、ブラウザでを使用するために私のconfigureクラスを教えていましたエラーを取得します。

関連する問題