Manish Gautam
Manish Gautam

Reputation: 516

Angular 2 Http Get call with Basic Authentication

There are various questions related to the same concept, but somehow I am not able to figure out a simple HTTP Get call with Angular 2.

I have tried the same service with postman and it works, but not with a angular service.

My code looks like:

Service.js

let headers = new Headers({ 'Authorization': 'Basic ' +  btoa('[email protected]:password') });
let options = new RequestOptions({ headers: headers });

return this.http.get(Config.Api.GetNavbar, options).map((res: Response) => res.json());

I get a 401 Unauthorized error even if I am setting the headers.

Any help?

Upvotes: 0

Views: 4683

Answers (1)

Dan
Dan

Reputation: 21

I was facing exactly the same behavior when I was doing my first REST calls with Angular - it worked with Postman but didn't with Angular.

Some Browsers make a so called "preflight" call before the "real" AJAX call, and this first call caused the 401 Unauthorized response. The issue was that I was not allowing OPTIONS headers without authentication. The handling of OPTIONS headers was also in the restricted area but the authentication information was missing so the server send me back a 401 Unauthorized.

In the end the solution was to handle the OPTIONS requests outside of the restricted area. So the client receives now an OK for OPTIONS headers requests and goes on with the "real" call.

Since I have adjusted the request handling on server side everything works as expected.

Upvotes: 2

Related Questions