2017-02-28 123 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