我正在尝试使用 ASP.NET Core 7 和 React 开发一个应用程序,我需要为所有请求实现防伪保护。我在网上研究了几天,尝试了各种解决方案;但是,我仍然不确定如何解决这个问题。
下面是我的代码,我可以解决任何其他问题。
程序.CS
builder.Services.AddAntiforgery(
{
options.Cookie.Name = "X-XSRF-TOKEN";
options.Header = "X-XSRF-TOKEN";
});
控制器
[Route("/Test2")]
[ValidateAntiForgeryToken]
[HttpPost]
public PostResponse Test2(PostRequest pr)
{
return RunVehCheck(pr);
}
反应(.js)
const getCSRFToken = async () => {
const response = await fetch("https://localhost:7277/Test2", {
method: "GET"
});
const csrfToken = await response.json();
return csrfToken;
}
useEffect(() => {
getCSRFToken();
}, []);
const handleSubmit = async (e) => {
e.preventDefault()
fetch("https://localhost:7277/Test2", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": getCSRFToken
},
body: JSON.stringify({
"vehicleReg": inputValue.current.value
})
})
.then((res) => {
if (res.status === 200) {
return res.json()
} else {
throw Error("Erro posting data");
}
})
.then((res) => {
console.log("Suucessfully send", res)
})
.catch((er) => {
console.log("Error fetching data", er)
})
}
我必须将这些位添加到 ASP.NET 方面(在startup.cs 中):
services.AddAntiforgery(options =>
{
options.HeaderName = "XSRF-TOKEN";
});
然后:
var antiforgery = app.ApplicationServices.GetRequiredService<IAntiforgery>();
app.Use((context, next) =>
{
var requestPath = context.Request.Path.Value;
// I only tested one page... you should be able to wild card this or just add each page as needed
if (string.Equals(requestPath, "/WebAPI/Inventory/EditInventoryItem", StringComparison.OrdinalIgnoreCase))
{
var tokenSet = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokenSet.RequestToken!,
new CookieOptions { HttpOnly = false });
}
return next(context);
});
我的前端是 Angular。它有一个组件,您可以使用该组件读取此 cookie 的值“XSRF-TOKEN”,并将其设置为每个请求上名为“XSRF-TOKEN”的标头。所以你也必须这样做。读取 cookie(它设置为 HttpOnly: false,因此您可以执行此操作),然后添加名称为“XSRF-TOKEN”的自定义标头。不要在防伪选项中设置 cookie 名称。让 ASP.NET 处理它使用的 cookie。您只需要设置 HeaderName 即可。