How to set expiration date for ASP.NET_SessionId cookie? - asp.net

Here's how I have authentication configured in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Sigin"
name="MYCAUTH"
timeout="3000" />
</authentication>
How can I make both MYCAUTH and ASP.NET_SessionId cookies use expiration?

Try this:
DateTime expireDate = DateTime.Now.AddDays(30);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expireDate, true, string.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
Response.Cookies.Add(authenticationCookie);
FormsAuthentication.SetAuthCookie(userName, true);

var myCookie = Request.Cookies["myCookie"];
if (myCookie != null)
{
HttpCookie respCookie = new HttpCookie("myCookie", "MyValue");
respCookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Set(myCookie);
}

Related

Authentication does not save cookie

I have a login form where I should save into cookie the authentication in case the user close and reopen the browser.
I tried with
<authentication mode="Forms" />
With this code, I save the cookie into login
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(Login1.UserName, True, 600)
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
and here I read the cookie
Dim FormsAuthCookie As HttpCookie = Request.Cookies(FormsAuthentication.FormsCookieName)
Dim usr As String = FormsAuthCookie.Value
Dim Ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(FormsAuthCookie.Value)
usr = Ticket.Name & ""
The FormsAuthookie.value is always NULL, cannot understand what is wrong

Forms authentication for www and without www

This is part of my config file
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" enableCrossAppRedirects="true"
name="authtoken" domain="localsite.com" />
</authentication>
This is my method for authentication
public void Authenticate(string token, int userId)
{
var userData = new FormTicketUserData() {UserId = userId};
var ticket = new FormsAuthenticationTicket(1, token, DateTime.Now, DateTime.MaxValue,
false, userData.ToString());
var encryptString = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptString);
authCookie.Path = FormsAuthentication.FormsCookiePath;
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
HttpContext.Current.Response.Cookies.Add(authCookie);
HttpContext.Current.User = new MyFormsPrincipal(new FormsIdentity(ticket), userId);
UserContext.Refresh();
}
When I Authenticate on www.localsite.com,I don't Authenticate on localsite.com and vice versa.
When I Authenticate on www.localsite.com,I need be Authenticate on localsite.com too.
How can I do this.
This solved problem
authCookie.Domain = "localsite.com";

HttpContext.Current.User.Identity.Name is lost

I'm using ASP.NET forms authentication in my web application.recently i found a strange behavior. everything was working fine in production environment.with .net 4.0 and IIS 7.in the login user enter username and password and logged in then suddenly HttpContext.Current.User.Identity.Name is lost.this does not happen every time only in some occasions.i have unable to reproduce the issue in my development environment.i have checked if(HttpContext.Current.User.Identity.IsAuthenticated) it's also true authentication ticket user data is not empty also.only HttpContext.Current.User.Identity.Name is empty.plz help
code in Login button
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(txtUserName.Text.Trim(), Password.Text.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, // Version number
txtUserName.Text.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
if (Request.Cookies[txtUserName.Text] != null)
{
//HttpCookie myCookie = new HttpCookie(txtUserName.Text);
//myCookie.Expires = DateTime.Now.AddDays(-1d);
Request.Cookies[txtUserName.Text].Expires = DateTime.Now.AddDays(-1d);
Request.Cookies.Remove(txtUserName.Text);
}
HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
// HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
cookie.Expires = DateTime.Now.AddMinutes(60);
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
// cookie.Path = FormsAuthentication.FormsCookiePath;
FormsAuthentication.RenewTicketIfOld(ticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", txtUserName.Text.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
FailureText.Text = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="60" cookieless="UseCookies" defaultUrl="~/Landing.aspx" protection="All"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
Your session time is limited to 60 minutes. Does the problem only occur for people with an expired session? Might explain why you can't reproduce this on your development machine because you simply don't wait that long?

Forms authentication "Remember me" does not remembering me

I'm doing this:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserName,
DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
model.RememberMe, verification.UserId.ToString());
string hashedTicket = FormsAuthentication.Encrypt(ticket);
web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" defaultUrl="/" name="FunkyAuth" timeout="10000" />
</authentication>
and I check it like that:
protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie != null)
{
FormsAuthenticationTicket auth = FormsAuthentication.Decrypt(formsCookie.Value);
if (string.IsNullOrWhiteSpace(auth.UserData)) return;
int userId = int.Parse(auth.UserData);
var principal = new FunkyPrincipal(new GenericIdentity(auth.Name), userId);
Context.User = principal;
Thread.CurrentPrincipal = principal;
//Response.Cookies[FormsAuthentication.FormsCookieName] = formsCookie;
}
}
What am I doing wrong? Why it didn't persist it for long time?

asp.net login control - set user auth ticket expiration date

I wanna to overide expiration date of user auth ticket on login.aspx.
This code doen't work properly, because after 1 minute user is still authenticated.
private int loginExpire = 1;
protected void Login_LoggedIn(object sender, EventArgs e)
{
HttpCookie authCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket oldAuthTicket = FormsAuthentication.Decrypt(authCookie.Value);
var newAuthTicket = new FormsAuthenticationTicket(
oldAuthTicket.Version,
oldAuthTicket.Name,
DateTime.Now,
DateTime.Now.Add
(TimeSpan.FromMinutes(loginExpire)),
oldAuthTicket.IsPersistent,
oldAuthTicket.UserData,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(newAuthTicket);
authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Set(authCookie);
FormsAuthentication.RedirectFromLoginPage(GetDestinationPage(lgUserLogin.UserName), false);
}
web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="1" slidingExpiration="true" protection="All"/>
</authentication>
Edit the forms element for authentication section in web.config: set timeout="1" and slidingExpiration="false"
Or instead of RedirectFromLoginPage method use code below:
String returnUrl;
if (Request.QueryString["ReturnURL"] == null)
{
returnUrl = "/Default.aspx"; //your default page url
}
else
{
returnUrl = Request.QueryString["ReturnURL"];
}
Response.Redirect(returnUrl);

Resources