Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting http interceptor to specific domain

Tags:

angularjs

I'm busy in building a little backoffice Web client in Angular.JS which directly talks to my API. For authentication I use OAUTH2 where I use an http interceptor to include the access token to a request. But, the interceptor is global, so not only my requests/responses to the API are checked, but also any other http call, like static html and templates.

I would like to bind the interceptor to my API calls only.

Would this be possible without a nasty domain-string-comparing-if-statement in the interceptor?

like image 312
Pepster Avatar asked May 31 '14 08:05

Pepster


1 Answers

You can create a service-wrapper around $http that takes care of OAuth specific stuff (e.g. adding a header etc) and use that service (instead of $http) for OAuth related requests.


Sample implementation:

app.factory('HttpOAuth', function ($http) {
    // Augments the request configuration object 
    // with OAuth specific stuff (e.g. some header)
    function getAugmentedConfig(cfg) {
        var config  = cfg || {};
        config.headers = config.headers || {};
        config.headers.someHeaderName = 'some-header-value';
        return config;
    }

    // The service object to be returned (`$http` wrapper)
    var serviceObj = {};

    // Create wrappers for methods WITHOUT data
    ['delete', 'get', 'head', 'jsonp'].forEach(function (method) {
        serviceObj[method] = function (url, config) {
            var config = getAugmentedConfig(config);
            return $http[method](url, config);
        };
    });

    // Create wrappers for methods WITH data
    ['post', 'put'].forEach(function (method) {
        serviceObj[method] = function (url, data, config) {
            var config = getAugmentedConfig(config);
            return $http[method](url, data, config);
        };
    });

    // Return the service object
    return serviceObj;
});

See, also, this short demo.

like image 199
gkalpak Avatar answered Oct 12 '22 18:10

gkalpak