I am trying to add an option to my web page, so that when a user logs in to have a 'remember me' option. To implement this I am trying to store the user data (name+password) in a cookie, but it's not working at the moment.
My code to store the cookie is:
int timeout = 525600;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, true, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(model.UserName, true);
Request.Cookies.Add(cookie);
and on my logIn controller my code looks like:
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData;
}
The problem is that the userData cookie is always empty. What am I missing?
Try this.
Creating/Writing Cookies
Way 1
`HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);`
Way 2
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Way 3
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Reading/Getting Cookies
string roll = Request.Cookies["StudentCookies"].Value;
Deleting Cookies
if (Request.Cookies["StudentCookies"] != null)
{
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
Response.Redirect("Result.aspx"); //to refresh the page
}
reference here
Related
This is the code I use to store a cookie after user is authenticated.
var authTicket = new FormsAuthenticationTicket(
1,
Session["UserID"].ToString(), //user id
DateTime.Now,
DateTime.Now.AddDays(1), // expiry
true, //true to remember
"", //roles
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent) { cookie.Expires = authTicket.Expiration; }
Response.Cookies.Add(cookie);
What should I do next to retrieve this cookie when the user visits the site again ?
To get the cookie:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
To get the ticket inside the cookie:
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
Typical way of doing it-- implement AuthenticateRequest in global.asax.cs...something like this....
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
// Get the forms authentication ticket.
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new MyPrincipal(identity);
// Get the custom user data encrypted in the ticket.
string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
// Deserialize the json data and set it on the custom principal.
var serializer = new JavaScriptSerializer();
principal.User = (User)serializer.Deserialize(userData, typeof(User));
// Set the context user.
Context.User = principal;
}
}
...then, whenever any of your code needs to access the current user, just get the context user:
var user = HttpContext.Current.User;
Link
I want to use HttpCookie instead of Session in ASP.NET.
I'm facing problem when I set cookie in login page and redirect it to next page. If I try to access the cookie in the next page it returns null.
Login Page Code
HttpCookie loginCookie = new HttpCookie("LoginInfo");
loginCookie["EmailID"] = txt_email.Text;
loginCookie.Domain = ConfigurationManager.AppSettings["SiteURL"];
loginCookie.Expires = DateTime.Now.AddDays(30);
loginCookie.Secure = false;
loginCookie.Domain = "/";
Response.Cookies.Add(loginCookie);
Response.Redirect("home.aspx");
Home Page Code
HttpCookie loginCookie = new HttpCookie("LoginInfo");
if (loginCookie["EmailID"] == null)
{
Response.Redirect("Default.aspx");
}
You don't have to create a new Cookie instead retrieve the existing one using Request.Cookies
HttpCookie loginCookie = Request.Cookies["LoginInfo"];
See: How to: Read a Cookie - MSDN
The other thing to do is to remove setting Domain from your first code, You are setting it twice, Just comment out these two lines.
HttpCookie loginCookie = new HttpCookie("LoginInfo");
loginCookie["EmailID"] = txt_email.Text;
//loginCookie.Domain = ConfigurationManager.AppSettings["SiteURL"]; //This one
loginCookie.Expires = DateTime.Now.AddDays(30);
loginCookie.Secure = false;
//loginCookie.Domain = "/"; //and This one
Response.Cookies.Add(loginCookie);
Response.Redirect("home.aspx");
I have multiple cookies with the same name, domain and path, but different values. This is not by design - I am trying to fix this, but cannot delete them. I have tried multiple code variations. Here is one:
string[] cookies = Request.Cookies.AllKeys;
HttpCookie cookie;
string cookieName;
string cookieValue;
for (int i = 0; i < cookies.Count(); i++)
{
cookieName = Request.Cookies[i].Name;
if (cookieName == "ASP.NET_SessionId")
{
// Do not delete session cookie or we will be logged out
continue;
}
cookieValue = Request.Cookies[i].Value;
cookie = new HttpCookie(cookieName);
cookie.Value = "";
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
And here is another:
string[] cookies = Request.Cookies.AllKeys;
for (int i = 0; i < Request.Cookies.AllKeys.Count(); i++)
{
if (Request.Cookies[i].Name == "ASP.NET_SessionId")
{
// Do not delete session cookie or we will be logged out
continue;
}
Request.Cookies[i].Expires = DateTime.Now.AddDays(-1);
}
When I list the cookies in Request.Cookies, the "deleted" cookies show up with an expiration date of yesterday, but there are other cookies that show up with an expiration date of 1/1/0001. These are the ones that just won't take a hint and take a hike.
Help greatly appreciated.
Have you tried setting the expire date a year into the past instead of 1 day?
Here is a post on the deleting cookies. In his code he sets the date back 30 years.
Set the domain on the cookies.
cookieValue = Request.Cookies[i].Value;
cookie = new HttpCookie(cookieName);
cookie.Value = "";
cookie.Domain = "dev.domain.com";
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
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 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.
add this function to your global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
if (authTicket == null)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { '|' });
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
then you can use HttpContext.Current.User.Identity.Name to get username. hope it helps
HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
lbl_cookie_value.Text = cook.Value;
}
else
{
lbl_cookie_value.Text = "Empty value";
}
Reference Click here
In my application I use form authentication. My Authenticaton code is below:
public static void Authenticate(bool redirectToPage, ISecurityUser user, params string[] roles)
{
FormsAuthentication.Initialize();
GenericIdentity id = new GenericIdentity(user.UserName);
ExtendedPrincipal principal = new ExtendedPrincipal(id, user, roles);
//ExtendedPrincipal principal = new ExtendedPrincipal(id, user, new string[] { "1" });
string compressedPrincipal = ConvertPrincipalToCompressedString(principal);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, compressedPrincipal, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
//cookie.HttpOnly = false;
//cookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(cookie);
if (redirectToPage)
{
HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(user.UserName, true));
}
}
The user object contains FirmID and DealerID properties. After I login to application, I can replace FirmID and DealerID from the app. After changing process this code is runned:
public static void RefreshIdentitiy(ISecurityUser user)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
ExtendedPrincipal principal = ConvertCompressedStringToPrincipal(ticket.UserData);
principal.BindProperties(user);
FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, ConvertPrincipalToCompressedString(principal), ticket.CookiePath);
cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(newticket));
HttpContext.Current.Response.Cookies.Add(cookie);
}
My problem is that: When I open the app from second page, cookie of second page crushes the first page's. So FirmID and DealerID of first page is also changed.
When I open app from second page, I don't want cookie to crush another. What can I do about this issue?
you should do something like this on all your pages:
if(Request.Cookies[FormsAuthentication.FormsCookieName]!=null)
{
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.HttpOnly = false;
cookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(cookie);
}
Edit
My aim is to make sure you are not overwrite your cookies every time you go to a new page