Avatar of IUAATech
IUAATech

asked on 

Form authentication persistant cookie/ticket not working

My original code for creating a persistant Forms authentication cookie/ticket used to work perfectly before. However, (I believe) as a result of the recent upgrade to .NET Framework 3.5, it has stopped working and I have lots of people at work mad at me since their cookie expires after 10 minutes of inactivity.

The authentication setting in Web.Config file is pretty straight forward: <authentication mode="Forms" />

And my code for creating a user ticket uses the function CreateUserTicket and the redirection is handled by the function RequestLogin.

Even though both the cookies in the CreateUserTicket functions are set to expire after 30 days, the user is redirected to the login page after 10 minutes.

And the Page_Load code for Login.aspx is also attached. It basically checks to see if the user is authenticated.

Finally, I have a "Base Class" for all the aspx pages and the OnLoad Event checks to see if the the "UserInformation" cookie is valid or not:
public class BasePage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        if (User.Identity.IsAuthenticated && Request.Cookies["UserInformation"] == null)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("~/Login.aspx");
        }
        base.OnLoad(e);
    }
}

So my question is, what am I missing in my code. I have spent quite a deal of time researching this, but I haven't been able to fix this problem yet.

Please, any help would be appreciated. I am using .NET Framework 3.5
void CreateUserTicket(short userId, bool rememberMe, string userName, string application)
    {
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,
            Convert.ToString(userId),
            DateTime.Now,
            DateTime.Now.AddDays(30),
            rememberMe,
            UserProfileBLL.GetUserRoles(userName, application),
            FormsAuthentication.FormsCookiePath);
 
        // Encrypt the cookie using the machine key for secure transport
        string hash = FormsAuthentication.Encrypt(ticket);
        HttpCookie authCookie = new HttpCookie(
            FormsAuthentication.FormsCookieName, // Name of auth cookie
            hash); // Hashed ticket
 
        // Set the cookie's expiration time to the tickets expiration time
        if (ticket.IsPersistent)
        {
            authCookie.Expires = ticket.Expiration;
        }
        // Add the cookie to the list for outgoing response
        Response.Cookies.Add(authCookie);
 
        UserProfile userProfile = UserProfileBLL.GetUserProfile(userId);
        HttpCookie userInfoCookie = new HttpCookie("UserInformation");
        userInfoCookie.Values.Add("FirstName", userProfile.FirstName);
        userInfoCookie.Values.Add("LastName", userProfile.LastName);
        userInfoCookie.Values.Add("Email", userProfile.Email);
        userInfoCookie.Values.Add("App", application);
        userInfoCookie.Expires = DateTime.Now.AddDays(30);
        Response.Cookies.Add(userInfoCookie);
    }
 
    void RequestLogin()
    {
        // Redirect to requested URL, or homepage if no previous pagerequested
        string returnUrl = this.Request.QueryString["ReturnUrl"];
        if (returnUrl == null) returnUrl = ResolveUrl("~/Default.aspx");
 
        // Don't call FormsAuthentication.RedirectFromLoginPage since it
        // could replace the authentication ticket (cookie) we just added
        Response.Redirect(returnUrl);
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {
            RequestLogin();
        }
        else
        {
            ((Literal)Master.FindControl("liLoginStatus")).Visible = false;
            ((ComponentArt.Web.UI.Menu)Master.FindControl("Menu1")).Visible = false;
        }
    }

Open in new window

.NET ProgrammingASP.NETC#

Avatar of undefined
Last Comment
Ted Bouskill
ASKER CERTIFIED SOLUTION
Avatar of Ted Bouskill
Ted Bouskill
Flag of Canada image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of IUAATech
IUAATech

ASKER

I need to store user data (roles to be more specific) in the ticket. And as far as I know, FormsAuthentication.RedirectFromLoginPage method overwrites my cookie so my user data is then lost.

This is why I have implemented a separate redirect logic. I have seen numerous posts on the Web regarding this issue.
Avatar of Ted Bouskill
Ted Bouskill
Flag of Canada image

By the way, the following article has great information on this topic.
http://support.microsoft.com/kb/910443

However, why not use another cookie?  You don't have to stuff everything into one cookie.  I'm assuming you decided not to use a session variable as well.
Avatar of IUAATech
IUAATech

ASKER

Thanks. I have already been through that article.

And where do you want me to use another cookie? I am already using two cookies; one for storing the authentication ticket and the other for storing personal information like first name, last name, etc. And no, I have decided not to use session variable at this point since I think I can do away with session variables. Now that i think about it, maybe I should replace the "personal information" cookie with a session. Hmmmm...
Avatar of Ted Bouskill
Ted Bouskill
Flag of Canada image

Ah, I misread your code.  You are using a 2nd cookie already.  Therefore, don't touch the authentication cookie and let the standard 'Forms Authentication' do it's job.

Yes, it's a trade-off between a cookie and a session.  You get a faster response time for the session variables but too many active sessions can steal too much RAM and if they start serializing to disk it slows an application.

I never touch the authentication cookie.  In some applications I have used 4 separate cookies and session variables.

Cheers
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo