Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to logout user in OWIN ASP.NET MVC5

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")
            });
}
like image 909
Friend Avatar asked Oct 03 '14 16:10

Friend


2 Answers

I tried all this out:

System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

Request.GetOwinContext().Authentication.SignOut();

Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

but finally this solved my problem:

HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty),null);

Check

like image 199
nasir taha Avatar answered Nov 15 '22 21:11

nasir taha


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

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
like image 29
radbyx Avatar answered Nov 15 '22 21:11

radbyx