我有一个自定义 ActionFilterAttribute 确保 Session 中的值与数据库中的值匹配。如果值不匹配,它会将用户重定向到 AccountController 上的 Login 操作。
public class CheckSessionAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
{
// If the action allows Anonymous users, no need to check the session
return;
}
var session = filterContext.RequestContext.HttpContext.Session;
var userName = filterContext.RequestContext.HttpContext.User.Identity.Name;
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(userName).Result;
if (userName == null || user == null || session == null || session["ActiveSessionId"] == null ||
session["ActiveSessionId"].ToString() != user.ActiveSessionId.ToString())
{
session.RemoveAll();
session.Clear();
session.Abandon();
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new
{
action = "Login",
controller = "Account"
}
));
}
base.OnActionExecuting(filterContext);
}
}
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
SignOutAndKillSession();
ViewBag.ReturnUrl = returnUrl;
return View();
}
private void SignOutAndKillSession()
{
AuthenticationManager.SignOut();
Session.RemoveAll();
Session.Clear();
Session.Abandon();
}
}
当我被重定向到登录操作后再次尝试登录时,出现以下异常:
The provided anti-forgery token was meant for a different claims-based user than the current user
我在 Login 操作中设置了一个断点,可以看到在调用 SignOutAndKillSession() 之前和之后,User.Identity.Name 仍然设置为正在注销的用户。我相信这是导致页面呈现时生成不正确的 AntiForgeryToken 的原因。
有人可以帮我找出注销用户时如何清除用户主体吗?
谢谢