How to store multiple username and passwords in cookies in c#?
I tried But it stores only one username and password.
protected void Login_Click(object sender, EventArgs e)
{
if (chkRememberMe.Checked)
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
}
else
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
}
Response.Cookies["UserName"].Value = txtUserName.Text.Trim();
Response.Cookies["Password"].Value = txtPassword.Text.Trim();
}
Cookies are stored per-user, so your code should work as-is.
I would strongly recommend that you do not store usernames and passwords in user cookies though due to the security issues associated with this. Use the built-in authentication, which stores a session identifier instead.
Related
I can't for the life of me understand what I'm doing wrong here. I've searched high and low but everything I try doesn't seem to fix.
I'm trying to create a cookie that stores the first and last name of a user. If the user goes back and changes either the first or second name it should modify these subkeys in the userName cookie. This part doesn't seem to work though?
protected void btnContinue_Click(object sender, EventArgs e)
{
if (IsValid)
{
HttpCookie cookie = new HttpCookie("userName");
if (cookie != null)
{
Response.Cookies.Remove("userName");
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
else
{
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
cookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Order.aspx");
}
The way to delete cookies on the client browser is to override them, setting the expires value to a date in the past.
When you use this code:
Response.Cookies.Remove("userName");
you only delete the cookie on server, which Means it's not sent to the client. This Means the old cookie on the client is kept.
To delete the old cookie:
HttpCookie cookie = new HttpCookie("olduserName");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
Here 'oldusername' contain the previous value of 'username'.
Edit:
Another way is to name your cookie with a name that doesn't change, ever, then you can simply override it with the new value, when username changes.
Edit2:
I actually made the same mistake as you did, you should use:
Response.Cookies.Set(cookie);
When using Add there can be more than one Cookie with the same name. This is most likely your problem (sorry, I did not see that before).
Edit2:
Just saw this line now:
Response.Redirect("~/Order.aspx");
You are redirecting! Then the cookies are not set on the client.
Instead you should set the cookies in "~/Order.aspx".
I store the cookies when someone is logging in, as below:
List<User> listUser;
//returns 1 user
foreach(User u in listUser)
{
HttpCookie cookieNickname = new HttpCookie("UserNickname");
cookieNickname.Value = u.Nickname.ToString();
cookieNickname.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookieNickname);
HttpCookie cookiePassword = new HttpCookie("UserPassword");
cookiePassword.Value = u.Password;
cookiePassword.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookiePassword);
}
When someone visits the site again, I want to read data from the database which is associated with usernickname-cookie and userpassword-cookie.
Then I want to show the firstname and lastname on a label.
This is what I tried:
List<User> cookieLoggedInUser;
if (Request.Cookies["UserNickname"] != null && Request.Cookies["UserPassword"] != null)
{
//returns 1 user
cookieLoggedInUser = Database.SignIn(Request.Cookies["UserNickname"].ToString(), Request.Cookies["UserPassword"].ToString());
if (cookieLoggedInUser.Count > 0)
{
foreach (User u in cookieLoggedInUser)
{
lblFirstName.Text = u.FirstName;
lblLastName.Text = u.LastName;
}
}
}
But both of the Request.Cookies return null.
Why is that happening?
I wouldn't recommend the approach you took other then for experimeting purposes as it has big security risk.
To make your curent solution work check that you are creating cookies in the same domain where you consume them.
If it is not the case, browser will not send cookies to the other domain.
You can make the sign-in cookie permanent using a technique like this:
protected void Login1_OnLoggedIn(object sender, EventArgs e)
{
CheckBox Remember = (CheckBox)((Login)sender).FindControl("Remember");
if (Remember.Checked)
{
FormsAuthenticationTicket t = new FormsAuthenticationTicket(2, Login1.UserName, DateTime.Now, DateTime.Now.AddYears(5), true, "");
string data = FormsAuthentication.Encrypt(t);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, data);
authCookie.HttpOnly = true;
authCookie.Domain = "";
authCookie.Expires = t.Expiration;
Response.Cookies.Remove("FORMAUTH");
Response.Cookies.Add(authCookie);
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
}
This assumes the site is using asp.net membership services.
The line that says Response.Cookies.Remove("FORMAUTH"); should match the cookie name you have set up in your web.config under this section:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Login.aspx" name="FORMAUTH"/>
</authentication>
Wire this up to the OnLoggedIn event of your <asp:Login> control and when the user clicks Remember Me they stay logged in.
This is a lot safer than the alternative which you propose (storing unencrypted passwords in cookies).
I’m having some difficulty understanding how to access specific user data while using Forms Authentication.
I have already set up Forms Authentication for a User and an Admin.
When a User tries to log in, here is the code that runs:
protected void buttonLogIn_Click(object sender, EventArgs e)
{
string email = TextBoxEmail.Text.Trim();
string password = TextBoxPassword.Text.Trim();
UserType userType = UserType.User; //temporary value
string firstName = string.Empty;
string lastName = string.Empty;
bool success = DBAppLayer.AuthenticateLogIn(email, password, out userType, out firstName, out lastName);
if (success == true)
{
Session.Add("email", email);
Session.Add("firstname", firstName);
Session.Add("lastname", lastName);
switch (userType)
{
case DBDataLayer.UserType.User:
FormsAuthenticationUtil.SetAuthCookie(email, "User,", false);
Response.Redirect("~/User/UserDashboard.aspx", false);
break;
case DBDataLayer.UserType.Admin:
FormsAuthenticationUtil.SetAuthCookie(email, "Admin", false);
Response.Redirect("~/AdminArea/AdminDashboard.aspx", false);
break;
}
}
else
{
labelError.Text = "Bad username/password.";
}
}
This successfully redirects a User to their dashboard. Now when the User is in /User/UserDashboard.aspx, I want to display the User’s profile information that is stored in the database, such as the User’s job and age.
The problem is, I’m not sure how to access this specific User’s data in UserDashboard.cs. Do I need to create an Authentication Ticket? If so, would I do this in the login page?
Any links or suggestions would be appreciated.
It looks like your call to FormsAuthenticationUtil.SetAuthCookie passes in email as the user id when you create the authentication cookie. In your user dashboard page, the User.Identity.Name field will give you back this same email address. Use that value to call your database and get the user's profile.
You are also storing the email address in the Session so you could get it from there as well.
I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];
I've been implementing the Forms Authentication in ASP.NET with C# (v3.5).
I created a simple login form, when the users' email & passwords are stored in my SQL db.
When I login in my localhost, everything works just fine, but when I published the project and uploaded it on to my production web server, things got a little bit wierd for me.
The HttpContentxt.Current.User.Identity.IsAuthenticated variable return false, even if the login was successfull (and again, in localhost everything works fine).
This is the following login button click code (I'm using my own DataAccess, ignore it's irrelevant code):
protected void btnLogin_Click(object sender, EventArgs e)
{
Page.Validate("Login");
if (Page.IsValid)
{
string email = txtEmail.Text;
string passwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5");
WebFactory.DataAccess.Users.Data userData = new WebFactory.DataAccess.Users.Data(ConnectionString);
userData.Load(new WebFactory.DataAccess.Users.Item[] {
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Email, email),
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Password, passwd)
});
if (userData.HasData) // Login Success
{
if (!cbRememberMe.Checked)
{
FormsAuthentication.SetAuthCookie(userData.Id.ToString(), false);
}
else
{
FormsAuthentication.Initialize();
DateTime expires = DateTime.Now.AddDays(20);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userData.Id.ToString(),
DateTime.Now,
expires,
true,
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = expires;
Response.Cookies.Add(authCookie);
}
lblStatus.Text = "";
if (Common.QS.HasRefUrl)
{
Response.Redirect(Common.QS.RefUrl);
}
else
{
Common.UserTools.RedirectLoggedInUser(userData.Id);
}
}
else // Login failed
{
lblStatus.Text = "Email or password is wrong. please try again."
}
}
}
Thanks for all helpers, and sorry for the english mistakes.
Thanks all, I solved the problem.
I just needed to enter a name attribute in the <forms> clause and everything works perfectly now.
Thanks again!
Try checking the Forms Authentication Configuration in your web.config. Specifically the domain and path variables. The domain should match the domain of your website and the path should match the application folder name. You probably won't have one of these, so just set it to "/"
You can also set up tracing to make sure that the cookie is actually being read by the application.