如何在 Struts2 应用程序中为 AJAX 请求做 CSRF 保护

2022-01-16 00:00:00 csrf jquery ajax struts2 antiforgerytoken

我有一个 struts2 webapp,我需要在其中实现 CSRF 保护.对于统计表格,它非常简单.我只需要激活 tokenSession 拦截器 &然后在要提交的表单中设置.(在 这里 和 这里)

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 调用(我使用的是 jQuery)启用 CSRF 保护时,就会出现问题.在进行后续 AJAX 调用时,我面临重复使用令牌的问题.

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.

推荐答案

目前我已经通过为 AJAX 请求生成令牌并像这样以正常响应发送它来解决问题 -

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 方法.让被令牌激活的操作将其作为响应的一部分返回,这些操作将在不刷新页面的情况下重复执行.

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.

不过,我仍在寻找一个优雅的解决方案.

I am still looking for an elegant solution to this though.

相关文章