My WebAPI is, just that, an API backend for my UI to consume. In fact, I will have perhaps 10\'s of WebAPI services that my UI will use.
I\'m having difficulty understan
OK so. First up, you will need to be sending the XSRF token in a header. To do this you need to go to your ConfigureServices method and setup the AntiForgery service to expect this header.
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(x => x.HeaderName = "X-XSRF-TOKEN");
services.AddMvc();
}
Next you need to generate the token. Because the front end and API are different services, you will need to work out when you do this. You could do it when you login for example, or you could have a dedicated endpoint doing this but the end result is the same.
You can either return the token value in a header or cookie it's up to you. In my example I've used a Cookie which I'll explain later but you can use a header if you like.
public class HomeController : Controller
{
private readonly IAntiforgery _antiForgeryService;
public HomeController(IAntiforgery antiForgeryService)
{
_antiForgeryService = antiForgeryService;
}
public IActionResult GetToken()
{
var token = _antiForgeryService.GetTokens(HttpContext).RequestToken;
HttpContext.Response.Cookies.Append("XSRF-TOKEN", token, new CookieOptions { HttpOnly = false });
return new StatusCodeResult(StatusCodes.Status200OK);
}
}
The IAntiforgery service should already be able to be used (It's part of the "AddMVC" call you will be using already in .net core services).
OK, so now we have returned a cookie with a token value. Now we just need to be able to send it back.
Here is some jQuery doing the legwork
Now something to note is that AngularJS automatically does this. When $http is used, it goes and looks for a cookie named "XSRF-TOKEN", and it will then send it as a header automatically. Because you are using Vue you will basically be doing this anyway but a bit more of a manual process.
Also important to note, DO NOT set this up to expect the cookie back as the CSRF token. Otherwise you've defeated the entire purpose of CSRF anyway.
Then you can go ahead and decorate your actions/controllers with the AntiForgery attribute.
[AutoValidateAntiforgeryToken]
public class HomeController : Controller
{
In conclusion what it basically boils down to :
Mostly taken from here : http://dotnetcoretutorials.com/2017/05/18/csrf-tokens-angularjsjquery-asp-net-core/