Useful libraries
Swashbuckle
Swashbuckle is a library that automatically generates Swagger JSON and hosts a Swagger UI page. It’s a great way to document your API and test it out.
CSRF Tokens
ASP.NET Core can verify incoming requests using a CSRF token, so a random page on the internet can’t make a POST request to your endpoints. You can do this with individual attributes on your methods, or with a global `AutoValidateAntiforgeryToken` attribute.
To prevent an endpoint from being forgotten and left exposed, it’s a good idea to enable the automatic enforcement of the CSRF tokens unless you have a reason to disable it.
AJAX requests with CSRF tokens
In Startup.cs, you can set a header name that can be used as a CSRF token.
services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-Token";
});
You can make a JS variable available globally, which is much better than trying to get the value from random forms on your page.
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Csrf
<script>
document.csrfToken = "@Csrf.GetAndStoreTokens(Context).RequestToken";
</script>
Now you can use this token with whatever library you’re using to make background requests. Here’s an example with the Fetch API.
function csrfPost(url, body) {
return fetch(url, {
method: 'POST',
body: new URLSearchParams(body).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token': document.csrfToken
}
});
}