I've created a Web Forms Application
project only to test this case. I'm using the default web template of .NET4
framework without any modifications and 3 buttons and 1 label on the Default.aspx
page.
Buttons: btnLogin
, btnSetCookie
, btnGetCookie
Label: lblCookieInfo
Flow:
- Click Login
- Click
Set Cookie
button - Click
Get Cookie
button
Now, when i click the third button to retrieve the cookie, always throws me an error when reaches the Decrypt
method (Invalid value for 'encryptedTicket' parameter
).
When I try to retrieve the cookie into httpCookie
is blank without any value.
What am i doing wrong?
protected void btnLogin_Click(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie("myUserName", createPersistentCookie: true);
Response.Redirect("~/");
}
protected void btnSetCookie_Click(object sender, EventArgs e)
{
var ticket = new FormsAuthenticationTicket(1,
"myUserName",
DateTime.Now,
DateTime.Now.AddMinutes(10),
true,
"data value of cookie",
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
Expires = ticket.Expiration,
HttpOnly = true
};
btnGetCookie.Enabled = true;
Response.Cookies.Add(authCookie);
}
protected void btnGetCookie_Click(object sender, EventArgs e)
{
var httpCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
lblCookieInfo.Visible = true;
if (httpCookie == null)
{
lblCookieInfo.Text = "Cookie is Null";
return;
}
//Here throws error!
var decryptedCookie = FormsAuthentication.Decrypt(httpCookie.Value);
if (decryptedCookie == null)
{
lblCookieInfo.Text = "Cookie can't be decrypted.";
return;
}
lblCookieInfo.Text = string.Format("Name: {0}, Is Expired: {1}, Is Persistent: {2}, Expiration: {3}, Path: {4}, User data: {5}",
decryptedCookie.Name, decryptedCookie.Expired,
decryptedCookie.IsPersistent, decryptedCookie.Expiration,
decryptedCookie.CookiePath, decryptedCookie.UserData);
}