My app's server side is built in Asp.Net web api and the client side is angular 7.
I can find many examples of how to implement ValidateAntiForgeryToken when using web forms, angularjs, working with Razor and etc.
But I cannot find any article or quesion explaining how to implement this with web api and how to call it from the angular service.
Can someone show a short example of the server side and client side implementing this?
You can use a combination of the following:
Web api create antiforgery token guide
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
[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();
}
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',
}),
],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With