gpt4 book ai didi

javascript - 为 window.location.href 添加 CSRF token

转载 作者:行者123 更新时间:2023-11-28 04:55:59 27 4
gpt4 key购买 nike

我在 JavaScript 中的多个地方使用了 window.location.href。有没有通用的方法可以将 CSRF token 添加到所有这些 token 中?

Since the window.location is an object and window.location.href is one of its properties, we can't override it.

Writing a common function something like below and routing all the instances would be more manual and time consuming.

addCSRFAndProceed(url);
function addCSRFAndProceed (url) {
window.location.href = url + getCSRFTokenAndValue();
}

后端代码这是从我的后端设置 CSRF cookie 的代码。

$_COOKIE['CSRFTOKEN'] = '123456';

HTML 代码

<div class="redirect-button" onclick="TriggerRequest()">

Javascript代码

function TriggerRequest() {
window.location.href="www.mysite.com/?index.php&from=desktop";
}

我有不同的函数使用 window.location.href 并期望一个通用的解决方案将 token 附加到 url,因为手动附加到所有函数中会很忙。

最佳答案

让我从 Laravel 作为后端情况来说话(仅适用于我的示例中相关的 1 行,因为 token 必须来自某个地方)

<meta id="csrf" name="csrf-token" content="{{ csrf_token() }}">

会在元标记中输出带有 id csrf 的 csrf token 吗?

使用和修改重定向代码的效果如下:

addCSRFAndProceed(url);
function addCSRFAndProceed (url) {
window.location.href = url + '?token=' + getCSRFTokenAndValue();
}

function getCSRFTokenAndValue() {
return document.getElementById("csrf").getAttribute('content');
}

您还应该为后端编写代码来检查查询字符串参数token,然后仅返回请求的页面。 (服务器端验证)

伪代码(仍然不知道你的后端)

if ($query_string_array['token'] == 'accepted token') {
return view:page;
} else {
return error: token does not match;
}

关于javascript - 为 window.location.href 添加 CSRF token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552835/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com