尝试通过两个不同的选项卡登录时出现AntiforgeryValidationException [英] AntiforgeryValidationException when trying to login by two different tabs
问题描述
步骤: 登录页面在两个不同的选项卡中打开.
The steps: The login page is opened in two different tabs.
- 用户A来自选项卡1的日志(无问题)
- 用户B在不刷新选项卡2的情况下尝试登录. 重定向到400页.
- User A logs from Tab 1 (No issues)
- Without refreshing the tab 2, user B tries to log in. Redirects to 400 page.
(异常:Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException:提供的反伪造令牌用于与当前用户不同的基于声明的用户.)
(Exception: Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The provided antiforgery token was meant for a different claims-based user than the current user.)
有解决方案吗?
推荐答案
我同意@ matt-shepherd的观点,这是防伪令牌验证的正确行为.选项卡B处于过期状态,因为选项卡B中的令牌不反映我们已经在选项卡A中登录
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.
我在这里发布了另一个答案,因为在我的应用程序(使用asp.net核心标识和剃须刀页面的.Net Core 2.2)中,System.Web.Helpers.AntiForgery.Validate()
不可用.因此,我无法通过以下方式验证控制器操作中的令牌:由@ matt-shepherd建议.
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.
多亏了帕特里克·韦斯特霍夫(Patrick Westerhoff)的合并请求,我创建了一个从IAsyncAlwaysRunResultFilter继承的过滤器.NET Core 2.2代码库:
public class RedirectAntiforgeryValidationFailedResultFilter : IAsyncAlwaysRunResultFilter
{
public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if (context.Result is AntiforgeryValidationFailedResult)
{
context.Result = new RedirectToPageResult("/AntiForgeryError");
}
return next();
}
}
我创建了一个名为AntiForgeryError
的剃须刀页面.
I have created a razor page named AntiForgeryError
.
最后,我将我的应用程序配置为使用Startup.cs
中的RedirectAntiforgeryValidationFailedResultFilter
:
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);
这篇关于尝试通过两个不同的选项卡登录时出现AntiforgeryValidationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!