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

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

Related

Forms Authentication / Cookie Expiring too soon

I am having an issue with a cookie expiring too soon for an ASP.Net web application.
I have set the cookie to expire after 3 hours and have not set a timeout in the webconfig, yet the user is directed to the login screen after 1 hour.
If I set the cookie expiry time to 1 minute, it logs the user out after 1 minute, so I am guessing something else is overriding it after an hour, but I am not sure where to look.
My forms authentication and session state web config entries, as well as the code for creating the cookie and looking up the cookie can be seen below.
<sessionState mode="InProc" timeout="525600" />
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" name=".VRBAdmin" enableCrossAppRedirects="false" cookieless="UseCookies" />
</authentication>
<authorization>
protected void OnLogin(object sender, EventArgs e)
{
if (Membership.ValidateUser(this.uxUser.Text, this.uxPassword.Text))
{
string userData = string.Join("|", Roles.GetRolesForUser(this.uxUser.Text));
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
this.uxUser.Text, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddHours(3), // expiryDate
true, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
// Your redirect logic
Response.Redirect(FormsAuthentication.GetRedirectUrl(this.uxUser.Text, true));
}
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching roles in userData field then extract
string[] roles = authTicket.UserData.Split(new char[] { '|' });
// Create the IIdentity instance
IIdentity id = new FormsIdentity(authTicket);
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, roles);
// Set the context user
Context.User = principal;
}
}
If you use ASP.NET Member Provider, you should not create FormsAuthenticationTicket by yourself. You don't even need to manually create principal object inside Application_AuthenticateRequest event.
Instead, you want to let Membership Provider do all the heavy lifting.
Normally, session timeout should be twice smaller than authentication cookie timeout, because we need to free up resources.
<sessionState timeout="180" />
<authentication mode="Forms">
<forms ... timeout="360" />
</authentication>
protected void OnLogin(object sender, EventArgs e)
{
if (Membership.ValidateUser(this.uxUser.Text, this.uxPassword.Text))
{
FormsAuthentication.SetAuthCookie(this.uxUser.Text, RememberMeSet);
...
}
}
Also increase application pool timeout if your application doesn't have enough traffic.

After successful login, I get redirected to login page again ASP.NET C#

I have login page in which login control is used, everything works fine in local machine but not working on server. after successfull login without any bug or error it again redirecting to login page.
below is my code.
web.config
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin,user"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<authentication mode="Forms">
<forms name="RJD" domain="abc.net" loginUrl="Login.aspx" protection="All" slidingExpiration="true" defaultUrl="~/Admin/ApproveComments.aspx" timeout="60" path="/">
</forms>
</authentication>
protected void ctrLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
FormsAuthentication.Initialize();
clsAuthenticate objauthonticate = new clsAuthenticate();
try
{
objauthonticate.user = ctrLogin.UserName.Trim();
objauthonticate.Pasword = ctrLogin.Password.Trim();
if (objauthonticate.Authonticate())
{
HttpContext.Current.Session["user"] = objauthonticate.user.ToString();
CreateTicket();
e.Authenticated = true;
// FormsAuthentication.RedirectFromLoginPage(ctrLogin.UserName, ctrLogin.RememberMeSet);
Response.Redirect("~/Admin/ApproveComments.aspx");
}
else
{
e.Authenticated = false;
}
}
catch (Exception ex)
{
//throw ex;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "alert('" + ex.Message + "');", true);
}
}
private void CreateTicket()
{
clsAuthenticate oblogin = new clsAuthenticate();
string role = oblogin.getRoleByID(Session["user"].ToString());
FormsAuthentication.HashPasswordForStoringInConfigFile(ctrLogin.Password, "sha1");
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "Forms", DateTime.Now, DateTime.Now.AddMinutes(30), true, role);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
Response.Cookies.Add(cookie);
}
When a user authenticates to a Web site by using Forms Authentication, the server creates a cookie. The value of the cookie is an encrypted forms authentication ticket. The cookie is passed to the server on each request to the application, and the FormsAuthenticationModule class decrypts the cookie value and determines if the user is valid or not.
I think you have blow tag in your project web.config. remove it
...
<modules>
<remove name="FormsAuthentication" />
</modules>
....

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?

Resources