如何在 javaScript 中获取 CSRF 令牌值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32493454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:22:02  来源:igfitidea点击:

How to get CSRF token Value at javaScript

javascriptjquerycsrfwavemaker

提问by Niraj

I have requirement like that, when I send request, CSRF-tokenshould be send with it. I Explore some SO questions, But I can't find Solution.

我有这样的要求,当我发送请求时,CSRF-token应该与它一起发送。我探索了一些 SO 问题,但我找不到解决方案。

I have written Code like bellow to add token when request being sent,

我已经编写了如下代码来在发送请求时添加令牌,

 var send = XMLHttpRequest.prototype.send,
        token = $('meta[name=csrf-token]').attr('content');
    XMLHttpRequest.prototype.send = function(data) {
        this.setRequestHeader('X-CSRF-Token', "xyz12345");
        //this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
        return send.apply(this, arguments);
    }

This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.

这工作正常,但现在我需要在函数中添加 CSRF-Token 来代替xyz12345.

I have tried ajax function as below . `

我试过如下 ajax 功能。`

$.ajax({
            type: "POST",
            url: "/test/"
            //data: { CSRF: getCSRFTokenValue()}
        }).done(function (data) {
        var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
        if (csrfToken) {
            var cookie = JSON.parse($.cookie('helloween'));
            cookie.csrf = csrfToken;
            $.cookie('helloween', JSON.stringify(cookie));
        }

        $('#helloweenMessage').html(data.message);

    });

But it is not Yet Worked. So my question is: How to get js side CSRF-Token Value?

但这还没有奏效。所以我的问题是: 如何获得 js 端的 CSRF-Token 值?

采纳答案by Niraj

I get my CSRF Token by this way, By adding function :

我通过这种方式获得了我的 CSRF 令牌,通过添加功能:

$.get('CSRFTokenManager.do', function(data) {
   var send = XMLHttpRequest.prototype.send,
   token =data;
   document.cookie='X-CSRF-Token='+token;
   XMLHttpRequest.prototype.send = function(data) {
       this.setRequestHeader('X-CSRF-Token',token);
       //dojo.cookie("X-CSRF-Token", "");

       return send.apply(this, arguments);
   };
});

Where CSRFTokenManager.dowill be called from CSRFTokenManagerClass.
Now It is adding token in header and cookie in every request.

CSRFTokenManager.doCSRFTokenManagerClass中将在哪里调用。
现在它在每个请求的标头和 cookie 中添加令牌。