2017-02-28 4 views
1

Ich bin ziemlich neu in eckigen2, ich versuche, eine REST-Anfrage an eine lokale API mit Authentifizierungsinformationen von http-Header übergeben; Ich habe den folgenden Code:Senden von Authentifizierungsinformationen mit 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); 

aber ich bekomme 401: Nicht autorisiert. Wenn ich versuche POSTMAN alles richtig zu verwenden, funktioniert, ist die erzeugte Base64-codierte Token gleich, dass das Ziel der Anfrage ist:

[ 
    "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

Änderung der hTTP-Anforderung wie dieses return this.h ttp.post (URL, Eingabe, { Header: this.headers }). map (response => response.json()) –

Antwort

1

eine Anfrage mit der Authentifizierung wie folgt bilden:

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); 
      }); 
    } 

Dann auf dem Login-Aufruf die obige Funktion einreichen:

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

Versucht, immer noch das gleiche Problem – FrontTheMachine

Verwandte Themen