ASP.NET Forms authentication cookies - changing users
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 FormsCo开发者_StackOverflow社区okie = 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
FormsAuthentication.FormsCookieName
sets the cookie name, therefore there is only ever one authentication cookie as long as you name it with FormsAuthentication.FormsCookieName
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.
精彩评论