Logout a user in ASP.NET Identity

Introduction


In order to logout a user in ASP.NET Identity, we use the SignOut method.

SignOut


The SignOut method sign out a user by passing the appropriate authentication type as a parameter of the method.

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

The SignOut method is called by the AuthenticationManager which we can get from the OWIN context.

DefaultAuthenticationTypes


Multiple authentication types can be passed to the sign out method based on the used sign-in cookies in your application :

  • ApplicationCookie
  • ExternalCookie
  • ExternalBearer
  • TwoFactorCookie
  • TwoFactorRememberBrowserCookie

AuthenticationManager


We access the Authentication property to get the AuthenticationManager from the OWIN context.

IAuthenticationManager AuthenticationManager = HttpContext.GetOwinContext().Authentication;

Namespaces


In order to use the DefaultAuthenticationTypes object and the IAuthenticationManager object, you have to include the following namespaces :

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;

Example


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    IAuthenticationManager AuthenticationManager = HttpContext.GetOwinContext().Authentication;

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

    return RedirectToAction("login");
}

In the above example, We get the authentication manager from the OWIN context by accesing the Authentication property and then we use the SignOut method in order to sign out the logged in user. We redirect the user to the login view after the completion of the sign out operation.


The [ValidateAntiForgeryToken] attribute is used to prevent forgery of a request.