HTTP interceptor restriction for a specific domain

I am busy creating a small backoffice web client in Angular.JS that is directly related to my API. For authentication, I use OAUTH2, where I use an http interceptor to include an access token in the request. But the interceptor is global, so not only my API requests / responses are checked, but also any other HTTP call, such as static html and templates.

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

Would it be possible if there were no unpleasant domain-string-comparing-if statement in the interceptor?

+6
source share
1 answer

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


Implementation Example:

 app.factory('HttpOAuth', function ($http) { // Augments the request configuration object // with OAuth specific stuff (eg 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 .

+7
source

Source: https://habr.com/ru/post/970118/


All Articles