AspNetCore


Tags: csharp webdev
Reading time: about 1 minute

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
        }
    });
}

The following pages link here

Citation

If you find this work useful, please cite it as:
@article{yaltirakliwikiaspnetcore,
  title   = "AspNetCore",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/wiki/AspNetCore/"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "AspNetCore", December, 2024. [Online]. Available: https://www.gkbrk.com/wiki/AspNetCore/. [Accessed Dec. 17, 2024].
APA Style
Yaltirakli, G. (2024, December 17). AspNetCore. https://www.gkbrk.com/wiki/AspNetCore/
Bluebook Style
Gokberk Yaltirakli, AspNetCore, GKBRK.COM (Dec. 17, 2024), https://www.gkbrk.com/wiki/AspNetCore/

Comments

© 2024 Gokberk Yaltirakli