remember me(isPersistent) dont work on Forms authentication - asp.net

Here my cookie create code:
This is controller (model.RememberMe is a checkbox value)
int timeout = (model.RememberMe) ? (int) FormsAuthentication.Timeout.TotalMinutes : Session.Timeout;//4h
HttpCookie cookie = accountService.GetCookie(userId, model.RememberMe, timeout);
Response.Cookies.Add(cookie);
Logger.Debug("POST: AccountController LogOn end.");
result = returnUrl != null
? RedirectToLocal(returnUrl)
: RedirectToAction("Index", "Profile", new {id = userId});
Service method that's create cookie
public HttpCookie GetCookie(int userId, bool rememberMe, int timeout)
{
Logger.Trace("AccountService GetCookie start with arguments:" +
" userId = {0}, rememberMe = {1}.", userId, rememberMe);
var authTicket = new FormsAuthenticationTicket(
1,
Convert.ToString(userId),
DateTime.Now,
DateTime.Now.AddMinutes(timeout),
rememberMe,
string.Empty,
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Logger.Debug("Cookie for user with userId = {0} has created", userId);
Logger.Trace("AccountService GetCookie end.");
return cookie;
}
But unfortunately RememberMe dont work and cookies expires at the end of the browser session.Why?
What is the purpose of FormsAuthenticationTicket isPersistent property? Here some kind of answer but i dont understand why it doesnt work?

The difference between your code and the SO answer that you linked is that they use:
FormsAuthentication.SetAuthCookie(model.UserName, true);
Which makes the cookie with proper expiration time based on the IsPersistent property. However, if you return the cookie with the constructor like in your code:
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Then the expiration time will be set to browser-session because that is the default behavior of the HttpCookie class: what is the default expiration time of a cookie
So you probably have two options. Use the FormsAuthentication.SetAuthCookie method outlined in the answer you linked to, or add:
cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want

Related

Cookies in ASP.NET-Call Back to another page

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?

ASP.NET MVC Remember me

I've got a project based in ASP.NET MVC 4 that simple authentication.
I'm trying to get my site to automatically log the user in when they check the remember me checkbox. However I'm having problems getting this working. After closing down the browser and reopening it the user is never logged in.
After checking (http://forums.asp.net/t/1654606.aspx#4310292) I've added a machine key in, generated by IIS. I've set automatically generate at runtime and generate a unique key for each application have both been disabled and I've Generated Keys). Unfortunately this hasn't worked.
Looking at "Remember me" with ASP.NET MVC Authentication is not working, I've added in the line FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe) but that didn't work either so I've now commented it out.
I tried the answer given on ASP.NET MVC RememberMe but that doesn't seem to work either.
Am I missing something obvious?
//FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (model.RememberMe)
{
//int timeout = model.RememberMe ? 525600 : 2; // Timeout in minutes,525600 = 365 days
int timeout = 525600;
var ticket = new FormsAuthenticationTicket(model.UserName, model.RememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);//My Line
Response.Cookies.Add(cookie);
}
this is how i do it
public class MyAuthentication
{
public static HttpCookie GetAuthenticationCookie(LoginModel model, bool persistLogin)
{
// userData storing data in ticktet and then cookie
JavaScriptSerializer js = new JavaScriptSerializer();
var userData = js.Serialize(model);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
"akash",
DateTime.Now,
DateTime.Now.AddHours(1),
persistLogin,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie= new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Expires = authTicket.Expiration; //must do it for cookie expiration
return cookie;
}
internal static bool Login(string UserName, string Password)
{
//UserName="akash" Password="akash"
//check can be done by DB
if (UserName== "akash" && Password == "akash")
return true;
else
return false;
}
}
and then
[HttpGet]
[AllowAnonymous]
public ActionResult Login()
{
//ViewBag.Message = "Your contact page.";
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
// var ek = cookie.Value;
try
{
//some times no cookie in browser
JavaScriptSerializer js = new JavaScriptSerializer();
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
//string data = ticket.UserData;
LoginModel model = js.Deserialize<LoginModel>(ticket.UserData);
if (MyAuthentication.Login(model.UserName, model.Password) == true)
{
RedirectToAction("Index", "Home");
}
}
catch
{
}
return View();
you can check it on Global.asax or authorization filter.
make sure you have web.config has
<authentication mode="Forms">
<forms defaultUrl="/Home/Login" loginUrl="/home/Login" timeout="2880">
</forms>
</authentication>
and [Authorize] attribute before all controller.
builder.Services.AddControllersWithViews();
var constr = builder.Configuration["ConnectionStrings:Default"];
builder.Services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSqlServer(constr);
});
builder.Services.AddIdentity<AppUser, IdentityRole>(opt =>
{
opt.Password.RequiredLength = 8;
opt.Password.RequireDigit= true;
opt.Password.RequireLowercase= true;
opt.Password.RequireUppercase= true;
opt.Password.RequireNonAlphanumeric= true;
opt.User.RequireUniqueEmail= true;
opt.Lockout.MaxFailedAccessAttempts= 5;
opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(10);
opt.Lockout.AllowedForNewUsers= true;
}).AddEntityFrameworkStores<AppDbContext
().AddDefaultTokenProviders();
builder.Services.AddSession(opt =>
{
opt.IdleTimeout = TimeSpan.FromSeconds(15);
});
builder.Services.ConfigureApplicationCookie(opt =>
{
opt.LoginPath = "/Auth/Login";
});
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();

Authenticating user with second login

asp.net I am using a second login control to verify a users email. They will get an Email that directs them to a confirm login window. Not the login that is used in the web.config file. So. I assumed that when they entered the loggedin event the would be authenticated, but it seems they are not. All I want to do here is set the profile property 'confirmed' = Y. So I added code:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox userName = (TextBox)Login1.FindControl("UserName");
string uname = userName.Text;
TextBox Password = (TextBox)Login1.FindControl("Password");
if (Membership.ValidateUser(userName.Text, Password.Text) == true)
{
BDrider bd = new BDrider();
string UserData = bd.getRidFromUsername(uname).ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
}
}
But on the IsAuthenticated line it returns false ???
Seems that you are creating the cookie and trying to "consume it" in the very same request. Unfortunately, this won't work. The forms authentication module will pick up the cookie and maintain the session starting from just the next request.
A possible workaround would be to redirect to an auxiliary page and perform your operation there and then redirect to Main.aspx. Your code would be then
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect( "Auxiliary.aspx" );
and in the Auxiliary.aspx:
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
However, I don't quite get the if. If you are just issuing the forms cookie, the user surely is authenticated. Why it would be otherwise?

Problem creating persistent authentication cookie: ASP.NET MVC

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;
}

Custom authentication doesn't work with asp.net 2.0

I'm trying to upgrade my mvc 1.0 application that had a custom written login. I assign the authcookie like this:
string _roles = string.Join(",", _ugr.GetUsergroupRoles(_username));
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
_username,
DateTime.Now,
DateTime.Now.AddHours(1),
false,
_roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
HttpContext.Response.Cookies.Add(cookie);
When I debug I got _roles = "Admin"
And I have an actionfilter that overrides OnExecuting where I have:
..
string[] _authRoles = AuthRoles.Split(',');
bool isAuthorized = _authRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));
if (!isAuthorized)
{
..
And here if I debug _authRoles has "Admin" in it, and isAuthorized is always false.
If I check the "ticket" it has some: UserData = "Admin".
What can be wrong there? Is it the "User.IsInRole" that is different, or do I need to add something in web.config?
/M
http://www.eggheadcafe.com/tutorials/aspnet/009e2e5e-5a44-4050-8233-59a0d69844e8/basics-forms-authenticat.aspx

Resources