如何在 Struts2 应用程序中为 AJAX 请求做 CSRF 保护 [英] HOWTO do CSRF protection in Struts2 application for AJAX requests

查看:40
本文介绍了如何在 Struts2 应用程序中为 AJAX 请求做 CSRF 保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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.

这篇关于如何在 Struts2 应用程序中为 AJAX 请求做 CSRF 保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆