Fetch using Cross Site Request Forgery (CSRF)
Need to post a request to service side method using fetch and CSRF. First tried the option of using credentials as this is secured and token authenticated. That didn't work so I need to use the MVC expected token authenticator header in this case of the Cross Site Request AntiForgery token.
Luckily for me it is written to the view as __RequestVerificationToken
so now post it into the header for verification and success.
Client side Request
const crsfToken = $("input[name^=__RequestVerificationToken]").first().val();
const requestUrl = 'url-to-request';
fetch(requestUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
"__RequestVerificationToken": crsfToken
},
body: JSON.stringify(policy)
})
.then((response) => response.json())
.then((data) => {
successFn(data.text);
})
.catch((error) => {
console.error('Error:', error);
failureFn("Unable to process request");
});
Server side MVC handler
[HttpPost]
public ActionResult TheUrl(CurrentModel model)
{
...
Stuff happens here
...
return new JsonResult
{
Data = new
{
text = <Response goes here ( it is text in this case )>
}
};
}
And it works