2017-02-28 120 views
1

我很新的angular2,我試圖做一個REST請求本地API與身份驗證憑據通過http頭;我得到了以下代碼:發送身份驗證憑據與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:未經授權。 如果我嘗試使用郵差一切正常,生成的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

變化的http請求這樣 回報this.h ttp.post(URL,input,{ headers:this.headers })。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