Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

csrf - 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');
    }])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
            }
        }    
    });
}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...