I am attempting to develop an application using ASP.NET Core 7 with React, and I need to implement Antiforgery protection for all requests. I have been researching online for a few days and have experimented with various solutions; however, I am still unsure how to resolve the issue.
Below is my code, and I am available to address any additional questions.
Program.CS
builder.Services.AddAntiforgery(
{
options.Cookie.Name = "X-XSRF-TOKEN";
options.Header = "X-XSRF-TOKEN";
});
Controller
[Route("/Test2")]
[ValidateAntiForgeryToken]
[HttpPost]
public PostResponse Test2(PostRequest pr)
{
return RunVehCheck(pr);
}
React (.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)
})
}
I had to add these bits to ASP.NET side of things (in startup.cs, ConfigureServices):
then (in Configure) :
Also see MS docs here: https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-7.0#generate-antiforgery-tokens-with-iantiforgery-1
My front-end is Angular. It has a component you can use that reads the value of this cookie, "XSRF-TOKEN", and sets that as a header called "X-Xsrf-Token" on each request. So you'd have to do the same. Read the cookie (it's set as HttpOnly: false, so you can do that), and then add a custom header with name of "X-Xsrf-Token". Don't set the cookie name in antiforgery options. Let ASP.NET take care of the cookie it uses. You only need to set the HeaderName to match the header you set from front-end.