Session ASP.NET Timeout
I am having problems with sessions in asp.net. I searched the website for a while but couldn't find the reason why it doesn't work. The session disappears after a few minutes. This is a project not created by me, I am not a hero in aspx. But I am trying to solve this problem.
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Default.aspx" timeout="120" slidingExpiration="true" />
</authentication>
<customErrors mode="RemoteOnly"/>
<httpRuntime requestValidationMode="2.0"/>
<pages validateRequest="false" />
<sessionState mode="InProc" cookieless="false" timeout="120" />
</system.web>
Checking the login to the pages you need to login if (! Functions.isLoggedIn (Session)) {Response.Redirect ("Default.aspx"); } Functions
public static bool isLoggedIn(HttpSessionState session)
{
return session["user"] != null;
}
Not logged in? Displaying the login form, filling out the form and submitting it to the server for validation
protected void Page_Load(object sender, EventArgs e)
{
if (Request["do"] != null)
{
switch (Request["do"])
{
case "logout":
Session.Abandon();
break;
}
}
if (Request.ServerVariables["REQUEST_METHOD"].ToLower() == "post")
{
//get username en password
string username = Request["username"];
string password = Request["password"];
if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password))
{
LoginMessage.Text = "Please fill in all the fields...";
}
else
{
password = FormsAuthentication.HashPasswordForStoringInConfigFile(
password,
"SHA1");
UserService gs = new UserService();
user g = gs.getUserByLogin(username, password);
if (g == null)
{
//wrong login
LoginMessage.Text = "Invalid username/password.";
}
else
{
//good login
Session["user"] = g;
System.Diagnostics.Debug.WriteLine("timeout:" + Session.Timeout);
Response.Redirect("Home.aspx");
}
}
}
}
GetUserByLogin function in user service
public user getUserByLogin(string username, string password)
{
user g;
var db = new projectName.Db.Models.projectnetContext();
IQueryable<user> query = from gb in db.users
where gb.username.Equals(username)
&& gb.Passwoord.Equals(password.ToLower())
&& gb.Status == 1
select gb;
if (!query.Any())
g = null;
else
g = query.First();
return g;
}
After logging in, creating a session
Session["user"] = g;
My problem is that I have set a timeout. But it doesn't seem to work. If I check the timeout on the server it is set to 120. But after 2 minutes I am redirected to the login form. Can I work it out? If I debug localhost it works, but not on the network.
The entrance works. The session is established (otherwise I would not be able to enter the following pages). If I go to another page (faster + + 5 minutes), I will still be signed in. Therefore the problem is reproductive.
Or, if this is not possible, Cookies? I usually work with cookies in PHP, but is there a way to do this in ASP.NET in a safe way?
source to share
There are two aspects to your scenario. You have authentication and session. These are two different things.
The session you are managing in your web.config has kept the value with a timeout of 120 minutes (2 hours)
But authentication also has a config section in web.config. https://msdn.microsoft.com/en-us/library/532aee0e%28v=vs.85%29.aspx
So what do you want to do first?
source to share
Please find this sample MVC controller action method.
// POST: /Secure/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginFormModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.Login, model.Password))
{
using (var db = new DatabaseEntities())
{
var user = db.Users.Single(u => u.Login == model.Login);
Membership.UpdateUser(new MembershipUser("UserMembershipProvider", user.Login, null, null, null, null, true, false, DateTime.MinValue, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue));
#region Create Authentication Cookie
Response.Cookies.Add(MyAppFormAuthenticationCookie.Create(user, model.RememberMe));
#endregion
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(HttpUtility.UrlDecode(returnUrl));
}
if (model.UserFormType == UserType.Candidate)
{
return RedirectToAction("Index", "Dashboard", new { area = "Candidate" });
}
if (model.UserFormType == UserType.Recruiter)
{
return RedirectToAction("Index", "Dashboard", new { area = "Recruiter" });
}
if (model.UserFormType == UserType.SuperAdmin || model.UserFormType == UserType.Admin)
{
return RedirectToAction("Index", "Dashboard", new { area = "Admin" });
}
}
}
ModelState.AddModelError("", "Incorrect username and/or password");
return View("Index", model);
}
return RedirectToAction("Index", "Home");
}
In this example, you have:
- UPDATE user profile to set last connection date and others if you want ...
- CREATING an authentication cookie in a custom way for this example
- REDIRECTION to home page according to user type
So, do you have a similar approach for user authentication in your application?
EDIT1:
Typically, you should end the authentication process with something like this:
var authTicket = new FormsAuthenticationTicket("MyAuthTicket", rememberMe, timeout: 120);
var encryptAuthTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptAuthTicket) { Expires = authTicket.Expiration });
source to share