How to implement keep me logged in asp.net using login control and membership in asp.net
By adding a checkbox..
And if it's checked you have to create a cookie with authentication and if it's not checked you have to put it in session
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx
Another way is to implement a cookie that's not persistent if it's unchecked like that:
int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(userName, rememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
First you need to create Cookie on login button click as follows and Store the Login Detail in it
protected void btnLogin_Click(object sender, System.EventArgs e)
{
string username = txtUsername.Text;
string Password = txtPassword.Text;
// Create Cookie and Store the Login Detail in it if check box is checked
if ((CheckBox1.Checked == true)) {
HttpCookie mycookie = new HttpCookie("LoginDetail");
mycookie.Values("Username") = txtUsername.Text.Trim();
mycookie.Values("Password") = txtPassword.Text.Trim();
mycookie.Expires = System.DateTime.Now.AddDays(1);
Response.Cookies.Add(mycookie);
}
Response.Redirect("Default2.aspx");
}
then check if cookie exists (is remember me checked), if yes fill the details as follows-
protected void Page_Load(object sender, System.EventArgs e)
{
//check if cookie exist then login page from
if ((Response.Cookies("LoginDetail") != null)) {
//Username
string uname = Response.Cookies("LoginDetail").Values("Username").ToString();
string pass = Response.Cookies("LoginDetail").Values("Username").ToString();
Response.Redirect("Default2.aspx");
}
}
Related
do you know how cookies works on ASP.NET? could you tell me?
and how to call the cookies to another page?
i have login form, and i use cookies. but i can't call that cookies to another page. i want to use some data from login form (it's like domain name, username and password) to do change password from changepassword.aspx form.
somebody please help me.
void Login_Click(object sender, EventArgs e)
{
string adPath = "LDAP://mydomain.com"; //Path to your LDAP directory server
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
//string groups = adAuth.GetGroups();
string groups = txtUsername.Text;
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text,DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch(Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
</script>
this is how use cookies in login form.
how can i use cookies in change password form?
I'm trying to make a shoppingcart using a cookie.
Every item has a Id which is put into the cookie.
Now I'm trying to put my cookie values into a List but I can't really find how to do it.
I want every value to be in a seperate index, is this possible?
Making the cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
Response.Cookies.Add(myCookie);
Adding a Id on buttonclick:
protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyTestCookie"].Values.Add("", "3");
Response.Write(Request.Cookies["MyTestCookie"].Values.ToString());;
}
Try this
public void SetCookiesList(List<string> listOfCookies)
{
var req = HttpContext.Current.Request;
HttpCookie cookie = req.Cookies["cookieName"];
if (cookie != null)
{
var cookieVal = cookie.Value;
if (!string.IsNullOrEmpty(cookieVal))
listOfCookies.Add(cookieVal);
}
}
I've got a web site that implements its own Forms based login, and creates an authentication cookie like this:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID, DateTime.UtcNow, expiration, isPersistent, userFunctions);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Expires = expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
The variable "userFunctions" contains a comma-separated list of roles that the user is a member of.
In my Global.asax file I'm retrieving those user functions in the following way:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string[] roles = id.Ticket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
All this is working great. Or it was until I had to change it for a whole new bunch of users. The problem with the new users is that the "userFunctions" variable can get really long, and is way too long to store in a cookie (that is limited in size to something like 4k).
I would change my code to store the "userFunctions" in session, but session is not available to Application_AuthenticateRequest. I could possibly store the data in the application cache (maybe in a key/value pair) but I hesitate to do that as the application cache doesn't seem the 'right' place to put this data.
I probably will end up putting it in the application cache, but before I do I thought I'd ask and see if anybody has a better alternative?
Given that I cannot use Session to store user roles (as I cannot retrieve them before Authorization has taken place), and I didn't want the expense of making a trip to the database on every page request, I ended up storing the roles in the Application Cache:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string[] roles;
string cachedRoles = (string)HttpContext.Current.Cache.Get("UserFunctions" + id.Name.ToLower());
if (cachedRoles == null)
{
// Reload UserFunctions and add back in to Cache.
cachedRoles = [...code to get UserFunctions from database...];
HttpContext.Current.Cache.Insert("UserFunctions" + id.Name.ToLower(), cachedRoles, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), System.Web.Caching.CacheItemPriority.NotRemovable, null);
}
roles = cachedRoles.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
It seems to work ok (though with limited testing so far).
OK, here's my code to create an authentication cookie:
// get user's role
List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
List<string> rolesList = (from r in roles
select r.ToString()).ToList();
string[] rolesArr = rolesList.ToArray();
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddDays(90),
createPersistentCookie,
String.Join(";",rolesArr) //user's roles
);
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
//FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
And here's my code in Global.asax to set the user roles into the user identity:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
catch
{
return;
}
}
However, if "createPersistentCookie" is TRUE in the top example, no persistent cookie is created. If I uncomment the last line like so:
//System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
then the persistent cookie is created on my hard drive. BUT then in the Global.asax code, the UserData field in "authTicket" is blank, so I can't set up the roles properly!
So I have to use SetAuthCookie to create a persistent cookie, but then for some reason the UserData field disappears from the persistent cookie.
What is the answer to this??
To create a persistent cookie you need to set the Expires property:
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
}
Does anyone know why ASP.NET Forms Authentication does not work on windows safari, or better yet, how to get it to work? It seems like a very weird issue. When I use a login control (System.Web.UI.WebControls.Login) everything works fine, but if I try to do a custom Forms Authentication login when I call FormsAuthentication.RedirectFromLoginPage safari just sends me back to the login page as if I'm not authenticated whereas every other browser logs me in and sends me on my way.
protected void lnkLogin_Click(object sender, EventArgs e)
{
if (Membership.Provider.ValidateUser(txtUsername.Text, txtPassword.Text))
{
Session.Clear();
HttpContext.Current.Response.Cookies.Clear();
FormsAuthentication.SetAuthCookie(txtUsername.Text, true);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
}
Try either SetAuthCookie, or RedirectFromLoginPage. The redirect needs to know where to redirect to anyway (ReturnUrl), maybe that is your problem.
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage("someuserid", false);
}
else
{
FormsAuthentication.SetAuthCookie("someuserid", false);
Response.Redirect("~/SomePage.aspx");
}
This works fine for me in Safari:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//check login
User user = UserBAL.GetUser(Login1.UserName, Login1.Password);
//null and filled object check
if (user != null && user.Id > 0 && user.Roles != null && user.Roles.Count > 0)
{
e.Authenticated = true;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
Login1.UserName, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
string.Join("|", user.Roles.ToArray())); // User ata
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
//redirect
Response.Redirect(FormsAuthentication.GetRedirectUrl(
Login1.UserName,
false));
}
else
{
Login1.FailureText = "Login failed.";
}
}