2017-02-28 10 views
1

私はかなりangular2に慣れていますが、httpヘッダーで渡された認証資格情報でローカルAPIにRESTリクエストを作成しようとしています。私は次のコードを持っています:angular2で認証資格情報を送信

 let headers = new Headers(); 
     headers.append('Accept', 'application/json') 
     headers.append('Content-Type', 'application/json'); 
     headers.append('Authorization', 'Basic ' + btoa(user + ":" + password)); 
     let options = new RequestOptions({ headers: headers, withCredentials: true }); 

     return this.http.get("http://localhost:8080/api/test-credentials", options); 

しかし、私は401を取得しています。 私はPOSTMANのすべてが正常に動作する使用しようとすると、生成されたbase64でエンコードされたトークンはその要求の対象だが、同じである:

[ 
    "http://localhost:8080/api/test-credentials", 
    { 
     "method":null, 
     "headers":{ 
      "Accept":[ 
       "application/json"], 
      "Content-Type":["application/json"], 
      "Authorization":["Basic dXNlcjpwYXNzd29yZA=="] 
     }, 
     "body":null, 
     "url":null, 
     "search":null, 
     "withCredentials":true, 
     "responseType":null 
    } 
] 
+0

変更をこの 戻りthis.hのようなhttpリクエストmap(response => response.json()) –

答えて

1

は、このような認証で要求を行います。

public getRequestWithBasicAuth(url: string, data): any { 

     let headers = new Headers(); 
     headers.append("Content-Type", "application/json"); 
     headers.append("Authorization", "Basic " + data); 

     let requestoptions = new RequestOptions({ 
      method: RequestMethod.Get, 
      url: url, 
      headers: headers 
     }); 

     return this.http.request(new Request(requestoptions)) 
      .map((res: Response) => { 
       let jsonObj: any; 
       if (res.status === 204) { 
        jsonObj = null; 
       } 
       else if (res.status === 500) { 
        jsonObj = null; 
       } 
       else if (res.status === 200) { 
        jsonObj = res.json() 
       } 
       return [{ status: res.status, json: jsonObj }] 
      }) 
      .catch(error => { 
       return Observable.throw(error); 
      }); 
    } 

その後ログインコールに上記の関数提出について:

onLogin(formData) { 
    let url = this.global_service.base_path + 'something...'; 
    let data = btoa(formData.email.toLowerCase() + ':' + formData.password); 

    this.global_service.getRequestWithBasicAuth(url, data) 
     .subscribe(res => { 
     if (res[0].status == 200) { 
     // Do what you want after login.. 
     } 
     } 
} 
+0

同じ問題を抱えている、試しました。 – FrontTheMachine

関連する問題