How to logout user in OWIN ASP.NET MVC5

DmitryBoyko picture DmitryBoyko · Oct 3, 2014 · Viewed 40.3k times · Source

I have got a standard AccountController class of ASP.NET MVC5 project. When I try to log out user I am facing an error coz HttpContext is null. (I mean here HttpContext.GetOwinContext().Authentication is null)

So I cannot get how we can logout user when session ends...

In global.asax I have got this

protected void Session_Start(object sender, EventArgs e)
{
     Session.Timeout = 3; 
}

protected void Session_End(object sender, EventArgs e)
{
            try
            {
                 var accountController = new AccountController();
                 accountController.SignOut();
            }
            catch (Exception)
            {
            }
}

AccountController

public void SignOut()
{
      // Even if I do It does not help coz HttpContext is NULL
      _authnManager = HttpContext.GetOwinContext().Authentication;    

    AuthenticationManager.SignOut();


}

private IAuthenticationManager _authnManager;  // Add this private variable


public IAuthenticationManager AuthenticationManager // Modified this from private to public and add the setter
{
            get
            {
                if (_authnManager == null)
                    _authnManager = HttpContext.GetOwinContext().Authentication;
                return _authnManager;
            }
            set { _authnManager = value; }
}

Startup.Auth.cs has

 public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                ExpireTimeSpan = TimeSpan.FromMinutes(3),
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
}

Answer

radbyx picture radbyx · Jun 26, 2015

Assuming that you are using ApplicationCookie to store your login information.

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);