Log Out a User in MVC 5 Using a Custom ActionFilterAttribute

I have a custom ActionFilterAttribute that makes sure a value in the Session matches a value in the database. If the values don't match, it redirects the user to the Login action on the AccountController.

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();
    }
}

When I try to login again after being redirected to the Login action, I get the following exception:

The provided anti-forgery token was meant for a different claims-based user than the current user

I set a breakpoint inside the Login action and can see that User.Identity.Name is still set to the user that is being logged out, before AND after the call SignOutAndKillSession(). I believe this is what's causing an incorrect AntiForgeryToken to be generated when the page renders.

Can someone help me find out how to clear the User Principal when logging out a user?

Thanks


For anyone that runs into this issue, I solved it by expiring the cookies created by MVC 5 inside the CheckSessionAttribute. I also changed the attribute from an ActionFilterAttribute to an IAuthorizationFilter Attribute

public class CheckSessionAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext 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();

            ExpireCookie("ASP.NET_SessionId", filterContext);
            ExpireCookie("__RequestVerificationToken", filterContext);
            ExpireCookie(".AspNet.ApplicationCookie", filterContext);

            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(new
                {
                    action = "Login",
                    controller = "Account"
                }
            ));
        }

        return;
    }

    private void ExpireCookie(string name, AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.Cookies[name] != null)
        {
            filterContext.RequestContext.HttpContext.Response.Cookies[name].Value = string.Empty;
            filterContext.RequestContext.HttpContext.Response.Cookies[name].Expires = DateTime.Now.AddMonths(-20);
        }
    }
}
链接地址: http://www.djcxy.com/p/74440.html

上一篇: 如何在Highcharts中移动图例

下一篇: 在MVC 5中使用自定义ActionFilterAttribute注销用户