There's now a sample in the source code. The sample uses Angular 1.x. Building on that sample, by using a Filter for validation, here's a rough example. At Startup the token needs to be set:
public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
{
app.Use(next => context =>
{
if (!context.Request.Path.Value.StartsWith("/api/"))
{
// We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
}
return next(context);
});
…
}
Then a filter can be used to validate the token:
public class AntiforgeryValidationFilter : IAsyncActionFilter
{
private readonly IAntiforgery antiforgery;
public AntiforgeryValidationFilter(IAntiforgery antiforgery)
{
this.antiforgery = antiforgery;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (context.HttpContext.Request.Path.Value.StartsWith("/api/"))
{
await antiforgery.ValidateRequestAsync(context.HttpContext);
}
await next();
}
}
And then register the filter in Startup:
public void ConfigureServices(IServiceCollection services)
{
// Angular's default header name for sending the XSRF token.
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services
.AddMvc(options =>
options.Filters.Add(typeof(AntiforgeryValidationFilter)))
…
}