3

I am creating forms authentication cookies using the following code:

string formsCookieStr = string.Empty;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,                              // version
            username,                       // user name
            DateTime.Now,                   // issue time
            DateTime.Now.AddMinutes(30),    // expires
            false,                          // Persistence
            userRoleData                    // user data
    );
formsCookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie FormsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, formsCookieStr);
HttpContext.Response.Cookies.Add(FormsCookie);

If a second user tries to login from the same client machine before the first user has logged out, will the code above result in two cookies existing on the client? If so, how do I prevent this state of affairs? Thanks

2 Answers 2

2

FormsAuthentication.FormsCookieName sets the cookie name, therefore there is only ever one authentication cookie as long as you name it with FormsAuthentication.FormsCookieName

Sign up to request clarification or add additional context in comments.

1 Comment

Correct, doing Cookies.Add(name) will create or overwrite any cookie with that name (and same domain).
-1

Its Generally a Good Practice to Clear Response Cookies in your Login Page Load or while new Cookie is about to be created: Response.Cookies.Clear(); , so existing User's Ticket is cleared before adding a new ticket.

Having Said that, Your Response will have 2 cookies (for 2 users) in your Response, as you are manually creating a Cookie and adding it to the response.

2 Comments

but won't the FormsAuthentication.FormsCookieName be unique, and therefore the second cookie will overwrite the first on the client?
-1 No there will only be one cookie. Also I'm about 95% certain doing Response.Cookies.Clear() will do nothing but remove any cookies you added to the Cookies collection during this current request. If you want to delete cookies from a user you must ADD cookie to the response with the same name as the cookie you want to delete and send it down as a permanent cookie (has an expiration date) that is set in the past.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.