weixin_33691817 2017-09-13 21:52 采纳率: 0%
浏览 200

使用Ajax的无效CSRF令牌

I am using purely javascript to access to certain web services built with Spring. when I tried to use an Ajax Post call to one of the services I encountered the issue with CSRF.

The Ajax call is the lines of:

var data = {'attribute1':'1','attribute2':'2'};

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: function(data)
    {   
        if (typeof inputId !== 'undefined') {
            $("#"+inputId).val(JSON.stringify(data));
        }
        console.log(JSON.stringify(data));    
    }
  });

I have been searching the web, but all that I found is to update the backend (JSP, PHP) to populate the attribute "${_csrf.parameterName}" in the form. However, I am not using any backend, all the page is HTML and javascript only.

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2017-09-13 22:19
    关注

    CSRF_Token is a cookie sent down and stored in the browser by the your web framework/server. Typically when posting via an ajax call as you're doing... you need to send that CSRF_Token value as part of your JSON data. To do that... you need to use JavaScript to find the cookie name and obtain the value. Than you need to assign the value to the right variable name that the server is expecting to see. For instance,

    var data = { crsf_token_name_server_expects: csrf_token_value_I_obtained };
    

    The CSRF_Token is used to ensure people communicating with your api actually accessed your site and created a valid session before trying to POST data to it. A user on google.com cannot post to stackoverflow.com unless stackoverflow.com set's something called a cors header which allows the communication between Google.com and Stackoverflow.com to go through.

    Based on your question... you said you're posting to a backend api which is powered by Java Spring. This api expects a csrf_token so it sounds like it's an api that is only supposed to be used for the domain name where this service is setup. For instance, a user goes to google.com and makes a POST to www.google.com/url_to_post_to/. Google would ensure a CSRF_Token is sent with this request... as they do not want people just randomly accessing this api url... without having a valid Google session.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog