How to set Request.IsAuthenticated to true when not using FormsAuthentication.RedirectFromLoginPage?

50,970

Solution 1

You need to update the current security principal for the request. When you call Response. Redirect(...) a new request is done and the security principal is reinitialized and Request.IsAuthenticated returns true in your case. FormsAuthentication.RedirectFromLoginPage internally calls Response. Redirect(...). You can manually renew the security principal for the current request like this:

public void RenewCurrentUser()
{
    System.Web.HttpCookie authCookie =
        System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = null;
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        if (authTicket != null && !authTicket.Expired)
        {
            FormsAuthenticationTicket newAuthTicket = authTicket;

            if (FormsAuthentication.SlidingExpiration)
            {
                newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
            }
            string userData = newAuthTicket.UserData;
            string[] roles = userData.Split(',');

            System.Web.HttpContext.Current.User =
                new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
        }
    }
}

Solution 2

FormsAuthentication.SetAuthCookie

Method Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.

Ref: msdn

Have a look at the Forms Authentication Control Flow. The authentication cookie is set to the response cookie collection, and should be observable at the http protocol level (e.g. use FireCookie or Fiddler2 to verify this).

Membership only verifies a username/password. Neither Membership nor SetAuthCookie() will modify the current request. They expect to send the cookie back to the caller, and the next request is when the properties like IsAuthenticated will return true.

Note that you can override and extend these automatic processes using custom IIdentity and IPrincipal, and hook into the authentication events if you need to.

Also have a look at Using Forms Authentication with ASP.NET AJAX

Solution 3

Redirecting after a POST is best practice, and should be considered the correct solution.

In some cases, you may still want to find out whether a user is authenticated within the scope of the authentication request (for instance if you are running additional logic after the authentication was performed which is shared with other requests).

In this case, you can reset the value of Request.IsAuthenticated with the following code:

// set the forms auth cookie
FormsAuthentication.SetAuthCookie(username, createPersistentCookie);

// reset request.isauthenticated
var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    if (authTicket != null && !authTicket.Expired)
    {
        var roles = authTicket.UserData.Split(',');
        System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
    }
 }

See post here: http://abadjimarinov.net/blog/2010/01/24/RenewUserInTheSameRequestInAspdotNET.xhtml

Solution 4

we can use this simply

FormsAuthentication.SetAuthCookie(username, true);

Share:
50,970
Amin Emami
Author by

Amin Emami

Software Engineer

Updated on August 29, 2020

Comments

  • Amin Emami
    Amin Emami over 3 years

    I am using Form Authentication and sending an Aajx request to the server for authentication. Based on the json result, the client decides where to go and what to do. That is the reason I am not using FormsAuthentication.RedirectFromLoginPage to not interfere the ajax/json response.

    In this case Request.IsAuthenticated returns false, even after validating the user with Membership.ValidateUser. Then I set the cookie using

    FormsAuthentication.SetAuthCookie(username, false);
    

    Although the second parameter, persistent cookie, is false, the cookie is still valid across browser sessions.

    Any idea how to make Request.IsAuthenticated work without using FormsAuthentication.RedirectFromLoginPage?