[Security]Automaticallally adding CSRF tokens to ajax cals when using jQuery--回転

2194 ワード

住所:http://erlend.oftedal.no/blog/?blogid=118
When building a ajax based aplication、you want to protect any POST request against  CSRF atacks.If you are using jQuery,then jQuery provides a lot of conventience methods for ajax cals($.get(), $.post(), $.getJSON()) etc.)and it would be a shamef you would have to duplicate adding CSRF tokens to all your ajax cals manualy or bygong back to  $.ajax(),because the conventience method didn't support the way You wanted to add the token.But jQuery,being the customizable frame ork it is,of course allows thers add thers kins of througventh.
Session based tokens
If You are using sesession based token s,you probably generaaa secure token when geneneraaathe session,and store that token in the session.When a request cost back to the server,chchecthat the the tokethe the the the tokeinininininininincleeeeeeeststststststrererererererererererererererererererererererererererererererererererererererererereeeeeeeeeeeee e e e e e e e e e e e e e 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 javascript variable.var csrf_token = '<%= token_value %>';Next,the trick is to bind to the global  ajaxSend イベント、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 abook I add the token as a request header、but you could optionally add it as a form post parameter in stead.
Doubl-submit of cookie
When using double submit of cookie,you adjust the example above to extract the value of  csrf_token from 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.