M. Barbieri
M. Barbieri

Reputation: 542

Basic Authentication Angular2 (Not CORS)

I am currently trying to call a jersey REST API that I have running locally on localhost:8080 through Angular 4 using HttpClient.

My Code: ```

ngOnInit() {
    const headers = new HttpHeaders();
    headers.append('Authorization', 'Basic ' + btoa('username:password'));
    headers.append('Content-Type', 'application/json');

    this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
      console.log(data);
    });
  }

```

When I make this call I get a 401 error saying that I am Unauthorized. However, when I run this through postman it goes through just fine. What am I doing wrong here?

NOTE: this is not a CORS issue, I am currently allowing CORS through an extension on firefox

Upvotes: 0

Views: 65

Answers (2)

David
David

Reputation: 34475

HttpHeaders are immutable, so you need to do something like that

ngOnInit() {
    const headers = new HttpHeaders()
    .append('Authorization', 'Basic ' + btoa('username:password'))
    .append('Content-Type', 'application/json');

    this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
      console.log(data);
    });
  }

Actually you should not need the Content-type here for a GET request

Upvotes: 2

woodykiddy
woodykiddy

Reputation: 6455

I think the issue is that you haven't passed in your custom request headers to HttpClient, which is causing the unauthorised error.

Please try something like this.

const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({headers: headers});

this.http.get('http://localhost:8080/mycall?myparam=myvalue', options ).subscribe(data => {
  console.log(data);
});

You can simply pass in your RequestOptions to http.get as it does accept headers as an optional parameter. Please check following link for more details on the usage.

https://angular.io/api/common/http/HttpClient#get

Also, remember to import RequestOptions as well.

Upvotes: 1

Related Questions