balteo
balteo

Reputation: 24679

Using AngularJs in order to retrieve a header from the response and set it on all requests

I am trying to use Angularjs in order to retrieve the csrf token from one of the response's header and set it on all requests.

I have managed to read it from the response using a response interceptor as follows:

 .factory('csrfResponseInterceptor', [function () {
        return{
            response: function(response){
                console.log(response.headers('X-CSRF-TOKEN'));
                return response;
            }
        }
    }])

but I am not sure how to set it on all requests afterwards.

Somehow I would need to set it using the $httpProvider service as follows:

$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');

I haven't managed to inject the $httpProvider into the interceptor though.

Can someone please provide advice on a best practice?

edit: This is how I register my interceptors:

.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
        $httpProvider.interceptors.push('httpResponseInterceptor', 'csrfResponseInterceptor');
    }])

Upvotes: 2

Views: 3739

Answers (2)

Lizzy
Lizzy

Reputation: 2163

You can use the same interceptor to intercept any request generating from your application and inject the token into it. For example:

.factory('csrfResponseInterceptor', [function () {
        var token = null;

        return{
            request: function(config){
                if(token){
                   config.headers['X-CSRF-TOKEN'] = token;
                }
                return config;
            },
            response: function(response){
                token = response.headers('X-CSRF-TOKEN');
                return response;
            }
        }
    }])

Upvotes: 2

dfsq
dfsq

Reputation: 193271

I think you can do it like this in config function:

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
    $httpProvider.interceptors.push(function() {
        return {
            response: function(response) {
                $httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.headers('X-CSRF-TOKEN');
                return response;
            }
        }    
    });
}]);

Upvotes: 4

Related Questions