Reputation: 12653
I have the following code to add authentication cookie to the response and redirect to homepage
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But in the Home.aspx, User.Identity.IsAuthenticated
is still false. why?
Upvotes: 1
Views: 3657
Reputation: 10941
You don't have to add the cookie to the response yourself.
You were doing this:
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But instead of doing a GetAuthCookie
and then adding it, you can just use SetAuthCookie
:
HttpCookie authCookie = FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("~/Home/Home.aspx");
When you look at the MSDN page for SetAuthCookie, you see that it not only adds the cookie to the Response (or the URL), but it also creates and encrypts a ticket:
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.
That's probably why it doesn't work when you just try to add the cookie yourself.
Upvotes: 1
Reputation: 12653
Finally got it working. Here is it in nutshell
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
I followed the code sample from this MSDN page:
Upvotes: 3