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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With