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

2023-06-14前端开发问题
3

本文介绍了如何在 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 保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

Rails 3.1 ajax:成功处理
Rails 3.1 ajax:success handling(Rails 3.1 ajax:成功处理)...
2024-04-20 前端开发问题
11

ExecJS::ProgramError: SyntaxError: 保留字“function"
ExecJS::ProgramError: SyntaxError: Reserved word quot;functionquot;(ExecJS::ProgramError: SyntaxError: 保留字“function)...
2024-04-20 前端开发问题
13