日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Security] Automatically adding CSRF tokens to ajax calls when using jQuery--转

發布時間:2025/4/5 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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.

轉載于:https://www.cnblogs.com/davidwang456/p/3607318.html

總結

以上是生活随笔為你收集整理的[Security] Automatically adding CSRF tokens to ajax calls when using jQuery--转的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。