zoukankan      html  css  js  c++  java
  • [Security] Automatically adding CSRF tokens to ajax calls when using jQuery--转

    地址:http://erlend.oftedal.no/blog/?blogid=118

    When building a ajax based application, you want to protect any POST request against CSRF attacks. If you are using jQuery, then jQuery provides a lot of convenience methods for ajax calls ($.get(), $.post(), $.getJSON() etc.) and it would be a shame if you would have to duplicate adding CSRF tokens to all your ajax calls manually or by going back to $.ajax(), because the convenience method didn't support the way you wanted to add the token. But jQuery, being the customizable framework it is, of course allows you to add these kinds of things through events.

    Session based tokens

    If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.

    To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.

    var csrf_token = '<%= token_value %>';

    Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request

    $("body").bind("ajaxSend", function(elm, xhr, s){
    if (s.type == "POST") {
    xhr.setRequestHeader('X-CSRF-Token', csrf_token);
    }
    });

    In the example above I add the token as a request header, but you could optionally add it as a form post parameter in stead.

    Double-submit of cookie

    When using double submit of cookie, you adjust the example above to extract the value of csrf_tokenfrom the cookies instead.

    Update: Bug in jQuery 1.5.0

    This does not work in jQuery 1.5.0 because of bug 8360. Looks like it will be fixed in 1.5.1. Works in 1.4.4.

  • 相关阅读:
    子程序的设计
    多重循环程序设计
    汇编语言的分支程序设计与循环程序设计
    代码调试之串口调试2
    毕昇杯模块之光照强度传感器
    毕昇杯之温湿度采集模块
    【CSS】盒子模型 之 IE 与W3C的盒子模型对比
    【css】盒子模型 之 概述
    【css】盒子模型 之 弹性盒模型
    【网络】dns_probe_finished_nxdomain 错误
  • 原文地址:https://www.cnblogs.com/davidwang456/p/3607318.html
Copyright © 2011-2022 走看看