在您之前进行身份验证后,登录时会出现该消息。
重现步骤:
1.) 打开您的登录页面并验证您未通过身份验证。
2.)复制选项卡并在第二个选项卡上登录。
3.) 返回第一个选项卡并尝试登录(无需重新加载页面)。
4.) 你看到这个错误;如果您的登录操作装饰有以下
[ValidateAntiForgeryToken]
属性:
System.Web.Mvc.HttpAntiForgeryException:
提供的防伪令牌用于用户“”,
但当前用户是“YourUserNameOrEmailAddress”。
[ValidateAntiForgeryToken]
此帮助器执行与属性相同的验证:
System.Web.Helpers.AntiForgery.Validate()
从登录操作中删除[ValidateAntiForgeryToken]
并改用此方法。
现在,当用户已经通过身份验证时,它将重定向到主页。
如果已通过身份验证,但以其他人身份登录,则注销当前用户并在以新用户身份进行身份验证之前继续验证防伪令牌。
if (User.Identity.IsAuthenticated)
{
if (User.Identity.Name == UserName)//User is already Logged in.
return RedirectToAction("Index", "Home");
else//Else: User is Logging In as someone else, so Log Out the Current User.
ResetUser();
}
System.Web.Helpers.AntiForgery.Validate();//Replaces [ValidateAntiForgeryToken].
//Add your Login Logic below here.
然后,添加此功能以安全地重置用户,而无需再次重新加载页面:
private void ResetUser()
{
//Add any additional custom Sign-Out/Log-Off Logic here.
Session.Abandon();
FormsAuthentication.SignOut();
//Source: https://stackoverflow.com/questions/4050925/page-user-identity-isauthenticated-still-true-after-formsauthentication-signout
//The User.Identity is Read-Only, but it reads from HttpContext.User, which we may Reset. Otherwise it will still show as Authenticated until the next Page Load.
HttpContext.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(string.Empty), null);//Do not set Identity to null, because other parts of the code may assume it's blank.
}
.net Core 想法:
我应该注意,如果您使用 .net Core 并且[AutoValidateAntiforgeryToken]
在您的控制器上有属性 - 或者您已经向整个站点添加了一个全局过滤器services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); });
- 那么您可以选择装饰您的登录操作避免自动验证异常的方法,并让您有机会在继续手动调用验证助手方法之前[IgnoreAntiforgeryToken]
重定向或注销。
注意:我还没有使用 .net Core 来验证这一点,但是在这里添加我的发现以防万一。