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

Amin Emami picture Amin Emami · Jan 20, 2010 · Viewed 48.9k times · Source

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?

Answer

Branislav Abadjimarinov picture Branislav Abadjimarinov · Jan 21, 2010

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);
        }
    }
}