FrontTheMachine
FrontTheMachine

Reputation: 526

Sending authentication credentials with angular2

I'm pretty new to angular2, I'm trying to make a REST request to a local API with auth credentials passed by http header; I got the following code:

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

but I'm getting 401: Unauthorized. If i try to use POSTMAN everything works correctly, the generated base64 encoded token is the same, that's the object of the request:

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

Upvotes: 3

Views: 3391

Answers (1)

Shailesh  kala
Shailesh kala

Reputation: 1872

Make a request with authentication like this:

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

Then on submitting the login call the above function:

  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..
        }
      }
}

Upvotes: 2

Related Questions