Bill McKnight
Bill McKnight

Reputation: 101

Restangular 1.4 setDefaultHeaders failing?

I am having trouble with Restangular 1.4 sending authorization headers to an external web api, which challenges if no such header is provided.

In the following code I try to set the default headers to include basic auth header, but when I look at Fiddler it tells me that no authorization header is present from the start, so the api call is rejected as unauthorized.

Does anyone know if this a bug in Restangular, or whether there is something lacking in the way I have tried to code the auth header?

angular.module('MyAPIService', ['restangular']).factory('MyAPIService', function (Restangular) {


Restangular.setBaseUrl('http://mywebapi/api/');
var encoded = Base64.encode(username + ":" + password);
Restangular.setDefaultHeaders({ Authorization: 'Basic ' + encoded });

return Restangular.one('users', username).get();

Upvotes: 1

Views: 1566

Answers (2)

Bill McKnight
Bill McKnight

Reputation: 41

Turns out that the issue is that the Authorization header is null for all preflight (i.e.) OPTIONS request. (to learn about them, see the section on Preflighted Requests at [https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). So since I was able to control the API's Basic Auth handling, I made the API not issue a 401 challenge for such preflight requests. The Authorization header was present on non-preflight requests (GET,POST,PUT,DELETE).

Upvotes: 1

Kairat Jenishev
Kairat Jenishev

Reputation: 123

Try to set headers in configuration block (not sure about factories). My code looks like this:

angular.module('app', ['restangular'])
    .config(['RestangularProvider', function (RestangularProvider) {
        // ... some code here

        RestangularProvider.setDefaultHeaders({
            token: 'some-secret-token'
            // other headers
        });

        // ... some code here
}]);

and works for me.

Upvotes: 1

Related Questions