You can use a combination of the following:
Web api create antiforgery token guide
- Setup the application
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
- Create the controller action that will get you the token. You can also do this in a filter.
[ApiController]
public class AntiForgeryController : Controller
{
private IAntiforgery _antiForgery;
public AntiForgeryController(IAntiforgery antiForgery)
{
_antiForgery = antiForgery;
}
[Route("api/antiforgery")]
[IgnoreAntiforgeryToken]
public IActionResult GenerateAntiForgeryTokens()
{
var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
Response.Cookies.Append("XSRF-REQUEST-TOKEN", tokens.RequestToken, new Microsoft.AspNetCore.Http.CookieOptions
{
HttpOnly = false
});
return NoContent();
}
- Apply it to every controller
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddMvc(options =>
{
options.Filters.Add(new ValidateAntiForgeryTokenAttribute());
});
//...
Now for the client side, you can use the built in antiforgery mechanism http angular guide
imports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'Enter chosen name',
headerName: 'Enter chosen name',
}),
],