問題描述
我有一個 struts2 webapp,我需要在其中實現(xiàn) CSRF 保護.對于統(tǒng)計表格,它非常簡單.我只需要激活 tokenSession
攔截器 &然后在要提交的表單中設(shè)置
.(在 這里 和 這里)
I have a struts2 webapp in which I need to implement CSRF protection. For statis forms it is pretty straight forward. I just need to activate the tokenSession
interceptor & then set <s:token/>
in the form to be submitted. (explained here and here)
但是當我需要為不一定通過表單提交的 POST AJAX 調(diào)用(我使用的是 jQuery)啟用 CSRF 保護時,就會出現(xiàn)問題.在進行后續(xù) AJAX 調(diào)用時,我面臨重復(fù)使用令牌的問題.
But the problem appears when I need to enable CSRF protection for POST AJAX calls (I am using jQuery) which are not necessarily submitted via forms. I face the issue of re-using token when making subsequent AJAX calls.
感謝任何指針或不同的方法.
Any pointers or different approaches are appreciated.
推薦答案
目前我已經(jīng)通過為 AJAX 請求生成令牌并像這樣以正常響應(yīng)發(fā)送它來解決問題 -
Currently I have resolved the issue by generating tokens for AJAX requests and sending it with the normal response like so -
Map<String, String> tokenInfo = Maps.newHashMap();
tokenInfo.put("struts.token.name", TokenHelper.getTokenName());
tokenInfo.put(TokenHelper.getTokenName(), TokenHelper.setToken());
我將從這個 & 中抽象出一個 util 方法.讓被令牌激活的操作將其作為響應(yīng)的一部分返回,這些操作將在不刷新頁面的情況下重復(fù)執(zhí)行.
I will abstract out a util method out of this & have the Actions that are token-activated to return this as part of response for actions which will be executed repeatedly without refresh of the page.
不過,我仍在尋找一個優(yōu)雅的解決方案.
I am still looking for an elegant solution to this though.
這篇關(guān)于如何在 Struts2 應(yīng)用程序中為 AJAX 請求做 CSRF 保護的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!