aspnet / Identity

[Archived] ASP.NET Core Identity is the membership system for building ASP.NET Core web applications, including membership, login, and user data. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.97k stars 871 forks source link

AntiForgeryTokens in Single Page Applications with ASP.Net Core Identity #1968

Closed ghost closed 5 years ago

ghost commented 5 years ago

Apologies if this isn't the right repository for this.

I'm trying to get AntiForgeryTokens working in a SPA (Single Page Application), and I'm ending up fighting with Identity.

I'm roughly following the instructions for configuring a Cookie with the AntiForgeryToken for use with Angular: https://github.com/aspnet/Docs/blob/master/aspnetcore/security/anti-request-forgery/sample/AngularSample/Startup.cs#L27

app.Use(next => context =>
{
  var tokens = antiforgery.GetAndStoreTokens(context);
  context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });

  return next(context);
});

I'm not actually using Angular, but I'm using Axios as a HTTP Client and it supports the same approach where the cookie value is read in and added as a header to the HTTP Request.

Asp.Net Core is configured to read that header using:

services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN";
});

This works fine most of the time, except for two situations.

The first issue is with Controller Actions that call signInManager.PasswordSignInAsync and signInManager.SignOutAsync.

These two methods make changes to the HttpContext.User, but those changes are only available for the next request, not the current request.

The second problem is that the tokens are generated before the Controller Actions are called.

This means that even if HttpContext.User was being set, it wouldn't have been set before the tokens are generated.

I tried changing the app.Use to set the cookie after next(context); but at that point the context.Response is already being sent to the user and cannot be modified.

I tried to have the Login action modify the cookie value, but HttpContext.Response.Cookies doesn't allow for modifying existing cookies.

ghost commented 5 years ago

Duplicate of: https://github.com/aspnet/Home/issues/2783