I am creating a cookie and storing the value of username after succesfull login. How can I access the cookie when the website is opened. If the cookie exist I want to fill the username text box from the cookie value. And how to decrypt the value to get the username. I am doing server side validation by getting the userdetails from the database. I am using vs 2010 with c#
FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (chk_Rememberme.Checked) { ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); }
cookie is created with name as .YAFNET_Authentication and content is encrypted
Webconfig:
<forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="15000" cookieless="UseCookies"/>
You can retrieve cookies using something like: var userName = Request. Headers. GetCookies("userName").
Name=Value: Cookies are stored in the form of name-value pairs. Path: Specifies the webpage or directory that sets the cookie. Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure).
You may use Request.Cookies collection to read the cookies.
if(Request.Cookies["key"]!=null) { var value=Request.Cookies["key"].Value; }
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With