I have getting issue with delete FormsAuthentication ticket cookie with remember me option.. it always showing expired date 01/01/0001, I am setting FormsAuthentication ticket with expired time at the time of login controller.
When the application URL open that time again check the expired time & Auth Cookie.
everytime it Authentication cookies expired time showing the same..
How to manage FormsAuth ticket with remember me option?
I have search a lots in different forums but not get the exact solutions..
Below screenshot when i have not selected Remember me.
When I selected remember me it showing time in Expire age. but not handling with C# code.
// Here u is view model object that set the username,password and remember me options.
// LOGIN FUNCTION CODE
if (u.RememberMe)
{
int timeout = u.RememberMe ? 525600 : (int)sessionSection.Timeout.TotalMinutes; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(1, u.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(timeout), u.RememberMe, logmodel.UserType);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Path = FormsAuthentication.FormsCookiePath;
//cookie.Expires = System.DateTime.UtcNow.AddMinutes(timeout);// Not my line
//if (ticket.IsPersistent)
// cookie.Expires = ticket.Expiration;
cookie.Expires = ticket.Expiration;
/// cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
else
{
FormsAuthentication.SetAuthCookie(u.Email, false);
}
Related
I am currently trying to replace our company wide user authentication that we use for all our internal web apps and what not as our current one was made in 2006 and fails on the regular. I was told to make it as simple as possible to implement on all existing projects. It is a .NET class library. It's .dll will be added as a reference to existing projects.
I am having an issue where I can log in exactly one time after all cookies have been cleared. Once I logout and log back in I get System.ArgumentException: Invalid value for 'encryptedTicket' parameter. I found some posts suggesting the cookie may be null, or I'm not trying to decrypt the name and not the value, but that wasn't the case. This happens on chrome and edge.
The user is authenticated every time though, assuming the correct username and password is used as I get redirected to the success page.
After authentication I add a cookie and then redirect.
private void AddCookie(int compID, bool persist, HttpContext httpContext)
{
httpContext.Request.Cookies.Add(SetUpSession(compID, persist));
FormsAuthentication.RedirectFromLoginPage(compID.ToString(), persist);
}
My method for creating the cookie
private HttpCookie SetUpSession(int companyID, bool persist)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
companyID.ToString(), // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
persist, // true to persist across browser sessions
FormsAuthentication.FormsCookiePath); // the path for the cookie
String encTick = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie("Cookie", encTick);
cookie.HttpOnly = true;
return cookie;
}
After I redirect to the success page there is a snipped of code that checks to see if the user is logged in. This is where the error happens
public dynamic isLoggedIn(HttpContext httpContext)
{
AuthenticationUtilities authUtil = new AuthenticationUtilities();
if (httpContext.Response.Cookies["Cookie"] != null)
{
companyID = authUtil.Authenticate(httpContext.Request.Cookies["Cookie"]);//the error occurs here
authUtil = new AuthenticationUtilities(companyID);
return authUtil;
}
else
{
httpContext.Response.Redirect("~/login.aspx");
return null;
}
}
The method that decrypts the cookie
public int Authenticate(HttpCookie cookie)
{
FormsAuthenticationTicket authTick = FormsAuthentication.Decrypt(cookie.Value);
return int.Parse(authTick.Name);
}
this method is called on any page that requires the user to be logged in, like this.
LMFJAuth.AuthenticationUtilities auth = _LMFJAuth.isLoggedIn(HttpContext.Current);//if the cookie is null it redirects to login.
This is the logout method
public void LogOut(HttpContext httpContext)
{
FormsAuthentication.SignOut();
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Expires = DateTime.Now.AddMinutes(-1);
httpContext.Session.Clear();
httpContext.Response.Cookies.Add(cookie);
httpContext.Response.Redirect(FormsAuthentication.LoginUrl);
}
Can somone help explain what may be going on in which the value for the encrypted ticked is coming up as invalid after the first successful login/logout?
For me it was that the encrypted value of cookie.Value was coming up as greater than the maximum value of 4096, being 4200 in my case. I had just added some role strings to the user data.
I found it help to look up the source code of Microsoft classes when I'm stuck, in this case I used:
http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8#0/untmp/whidbey/REDBITS/ndp/fx/src/xsp/System/Web/Security/FormsAuthentication#cs/1/FormsAuthentication#cs.
When I log I create the following cookie:
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
When I request data from this cookie, I use Request.Cookies:
string username = Convert.ToString(Request.Cookies["Ortund"]["Username"]);
When i log out, I do this:
HttpCookie cookie = new HttpCookie("Ortund");
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.Cookies.Add(cookie);
For some reason, now I'm sitting with a cookie that has an expiry date of 0001-01-01 12:00:00 AM in Request.Cookies["Ortund"] and the expiry date of the cookie doesn't change no matter how many times I log in.
Have I done something wrong here? Is this even close to how it should be done?
In your logout you are creating a new instance of the cookie. Also you are using Response.Cookies.Add which may allow multiple cookies of the same name to be appended to the Response.
I would suggest you to check the Request for the cookie key and if it doesn't exist add the cookie.
For updating the cookie, first get the existing cookie object and use Response.SetCookie to update the value.
Code
set
if(!Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
}
update
if (Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = Request.Cookies["Ortund"];
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.SetCookie(cookie);
}
I like to know how I can set the #User.Identity.Name via a cookie when a user clicks on a remember me checkbox.
Cookie code
if (_model.RememberMe)
{
HttpCookie cookie = new HttpCookie("login");
cookie.Values.Add("username", _model.Username);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
}
First login code
if (Membership.ValidateUser(Username,Password))
{
RememberMe();
FormsAuthentication.RedirectFromLoginPage(Username, false);
}
On the first login the Identity.name is set but when I close the browser and go back on to the site. it logs in correctly without the user putting in their credentials but the Identity.name is empty.
if (Request.Cookies["login"] != null)
{
// We know the automatic log in has worked as it comes into here...
}
What do I need to do once the user by passes the login page so I can setup the iPrincipal object?
Thanks
Try below code please
Note : please check it on page view not in the same method on creation of cokies
private void CreateCokies(string userName)
{
var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), true, userName);
string cookieContents = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
}
I am writing a "Remember My Username" Cookie that expires in a custom duration of time e.g. one month. I noticed that when I add HttpOnly = true, the expiration changes to session. Why is this? I can't seem to find any documentation on why this would happen.
Thanks.
Here is the documentation.
true if the cookie has the HttpOnly attribute and cannot be accessed
through a client-side script; otherwise, false. The default is false.
Basically, it becomes a session variable because it will only be stored on the server due to your setting
I'm adding the following code: Also, now I'm getting a different behaviors than the Title. I'm running this locally against the VS2010 built-in server. It seems to show inconsistent behaviors. I would move the HttpOnly = true before the Expires and after it and it seemed to change behavior until I refreshed the browser page. So, I am assuming everything was fine and never had an issue. In addition, I am moving HttpOnly and Secure flags to the web.config because not all my environments have SSL.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(strUserID, //name
false, //IsPersistent
24 * 60); // 24 hours
// Encrypt the ticket.
string encryTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
HttpCookie userCookie = new HttpCookie("Authentication", encryTicket);
userCookie.HttpOnly = true;
Response.Cookies.Add(userCookie);
e.Authenticated = true;
if (LoginPannelMain.RememberMeSet)
{
HttpCookie aCookie = new HttpCookie("email", strUserLogin);
aCookie.HttpOnly = true;
aCookie.Expires = DateTime.Now.AddYears(1);
Response.AppendCookie(aCookie);
}
else
{
HttpCookie aCookie = new HttpCookie("email", "");
aCookie.HttpOnly = true;
Response.AppendCookie(aCookie);
}
I am creating the cookie using the code below, How to read the txtusername value in another page and how to delete the cookie when I click sign out(code for sign out). I am new to programming please help.
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);
You should never store password as a cookie. That's a very big security threat. To delete a cookie, you really just need to modify and expire it. You can't really delete it, i.e. remove it from the user's disk. Check out this documentation.
Here is a sample:
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
Response.Cookies.Add(aCookie); // overwrite it
}
You cannot directly delete a cookie, you have to set it to expire before the current date:
if (Request.Cookies["clienDetails"] != null)
{
HttpCookie myCookie = new HttpCookie("clienDetails");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
You can read more about it here.
Furthermore I really encourage you to not write your own security but to read up on asp.net membership. More secure and easier to use. As I can see many flaws in your security model. Storing the password in plain text in a cookie is really really bad.
EDIT:
As you now changed your code, you have to do this to remove the cookie:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
FYI this did not work for me using Chrome 69 with the Continue where you left off feature enabled. Similar issue with Firefox. Disabling this feature worked for me.
See
Chrome doesn't delete session cookies
How to delete or expire a cookie in Chrome using Asp.Net
In my case this code worked:
Response.Cookies.Delete("access_token");
return Ok();