Search code examples
c#asp.netforms-authentication

Page.User.Identity.IsAuthenticated still true after FormsAuthentication.SignOut()


I have a page that when you press 'log out' it will redirect to the login.aspx page which has a Page_Load method which calls FormsAuthentication.SignOut().

The master page displays the 'log out' link in the top right of the screen and it displays it on the condition that Page.User.Identity.IsAuthenticated is true. After stepping through the code however, this signout method doesn't automatically set IsAuthenticated to false which is quite annoying, any ideas?


Solution

  • Page.User.Identity.IsAuthenticated gets its value from Page.User (obviously) which is unfortunately read-only and is not updated when you call FormsAuthentication.SignOut().

    Luckily Page.User pulls its value from Context.User which can be modified:

    // HttpContext.Current.User.Identity.IsAuthenticated == true;
    
    FormsAuthentication.SignOut();
    HttpContext.Current.User =
        new GenericPrincipal(new GenericIdentity(string.Empty), null);
    
    // now HttpContext.Current.User.Identity.IsAuthenticated == false
    // and Page.User.Identity.IsAuthenticated == false
    

    This is useful when you sign out the current user and wish to respond with the actual page without doing a redirect. You can check IsAuthenticated where you need it within the same page request.