Access Token Middleware AngularJS
If you are using angularJS in your application and your application need to process access token with each request, you can find a middleware in AngularJS known as "interceptors" (For more information on interceptors in AngularJS please go to this Link and search the page for "interceptors").
All you need to do is write a service factory where you insert the access token in every request
"config.headers['x-access-token'] = $window.sessionStorage.token;"
and then later register the service.
"$httpProvider.interceptors.push('oauthHttpInterceptor');"
angular.module('app', ['ngRoute'])
.factory('oauthHttpInterceptor', function ($window) {
// Factory to insert access token in every request
return {
request: function (config) {
if ($window.sessionStorage.token) {
config.headers['x-access-token'] = $window.sessionStorage.token;
}
return config;
}
};
})
.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider
.when('/sample/route', {
templateUrl: 'client/views/sample.html',
controller: 'SampleController'
})
// Register the service factory below
$httpProvider.interceptors.push('oauthHttpInterceptor');
}]);
The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptorsarray. The factory is called and injected with dependencies (if specified) and returns the interceptor.
There are two kinds of interceptors (and two kinds of rejection interceptors):
- request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
- requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
- response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new responseobject.
- responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
Happy Coding :)
very helpful
Nice .. Very helpful in my case .. thanks Ali Zaib
awesome