gotha
gotha

Reputation: 489

Angular 2 sending header for authorization

I am trying to get data from API that has oAuth authentication. What I am doing is sending the auth request from server1 (where my Angular app is) to server2 and I get the access token. Then I put the token in the JS variable and I am trying to access an API endpoint.

My js code looks like this:

let headers = new Headers({ 'Authorization': "Bearer " + oAuthAccessToken });
let options = new RequestOptions({ headers: headers });
let url = "http://example.com/api/getSomething"
this.http.post(url, body, options)
    .subscribe( res => {
         console.log(res.json())
});

The problem is that I am always getting "401 Unathorized". When I inspect the request in the Network tab of Chrome Dev Tools I see two strange things - first the request method is OPTIONS not POST and the header Authorization is missing.

Any idea what I might be doing wrong ? Why is the header not set ?

Edit:

The problem was that Angular sends OPTIONS request before the POST and my app firewall was expecting Authorization header to be always present. This header is not present in the OPTIONS request so I was getting Unauthorized. I changed my server app to send proper headers on OPTIONS request and now everything is fine.

Thanks for the help.

Upvotes: 0

Views: 1743

Answers (3)

Wahib Naseem
Wahib Naseem

Reputation: 11

Content-Type should be like below:

let header= new Headers({'Content-type':'application/x-www-form-urlencode'});    
header.append('Authorization',"Bearer " + token);
let opt= new RequestOptions({headers:header});  

Upvotes: 0

sreeramu
sreeramu

Reputation: 1223

As you are dealing with cross-domain requests, Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. so the option request is just to check is the server support CORS.

From : https://stackoverflow.com/a/21783145/3279156

Upvotes: 1

trollr
trollr

Reputation: 1115

I think the browser try to discover which http methods are allowed, so the first request is an request with the OPTIONS method. Usually the backend service answers with Access-Control-Allow-Methods inside the header. Afterwards the browser sends the real request.

I think that you need to allow CORS, then it should work as expected

Upvotes: 1

Related Questions