AntiforgeryValidationException when trying to login by two different tabs

允我心安 提交于 2019-12-24 00:23:14

问题


The steps: The login page is opened in two different tabs.

  1. User A logs from Tab 1 (No issues)
  2. Without refreshing the tab 2, user B tries to log in. Redirects to 400 page.

(Exception: Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The provided antiforgery token was meant for a different claims-based user than the current user.)

Any solution to handle this?


回答1:


I agree with @matt-shepherd that this is the correct behavior of the anti-forgery token validation. Tab B is in an expired state because the token in Tab B does not reflect that we have already logged in in Tab A the anti forgery token includes the username.

I am posting another answer here because in my app (.Net Core 2.2 using asp.net core identity and razor pages) System.Web.Helpers.AntiForgery.Validate() is not available.So I wasn't able to validate the token in the controller action as suggested by @matt-shepherd.

Instead I have created a filter inheriting from IAsyncAlwaysRunResultFilter thanks to Patrick Westerhoff's pull request that was merged to ASP.NET Core 2.2 code base :

public class RedirectAntiforgeryValidationFailedResultFilter : IAsyncAlwaysRunResultFilter
  {
    public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
      if (context.Result is AntiforgeryValidationFailedResult)
      {
        context.Result = new RedirectToPageResult("/AntiForgeryError");
      }

      return next();
    }
  }

I have created a razor page named AntiForgeryError.

At last, I have configured my app to use the RedirectAntiforgeryValidationFailedResultFilter in Startup.cs:

services.AddMvc(options => options.Filters.Add<RedirectAntiforgeryValidationFailedResultFilter>())
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



回答2:


This is the correct behaviour of the anti-forgery token validation. Tab B is essentially in an expired state. The only thing you can do here is to improve the way your system handles it.

I would recommend, for example, validating the token from within the controller action instead of using the attribute. To do this, just use this line as the first line of your Action: System.Web.Helpers.AntiForgery.Validate();. You can now catch any HttpAntiForgeryException thrown and respond to the user accordingly. e.g. telling the user that they're already logged in, or that they'll need to refresh the page, whichever is appropriate for your system.



来源:https://stackoverflow.com/questions/52760424/antiforgeryvalidationexception-when-trying-to-login-by-two-different-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!