I am facing a session issue After I close my browser my session expires, and after re-open browser, I have to log in again.
I don't want to expire my session on browser close.
I am using this in my web.config file:
<authentication>
<forms loginUrl="~/account/login" name="astroswamig" slidingExpiration="true" timeout="1000"></forms>
</authentication>
<sessionState mode="StateServer" cookieless="false" timeout="1000" />
and this in my controller:
string str = JsonConvert.SerializeObject(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.CustEmail, DateTime.Now, DateTime.Now.AddDays(120), true, str);
string enctryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCustCookie = new HttpCookie(FormsAuthentication.FormsCookieName, enctryptTicket);
authCustCookie.Domain = "xyz.com";
Response.Cookies.Add(authCustCookie);
The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here:
https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/
Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs.
Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here:
https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/
and also here:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples
Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs.
Related
Read about the SameSite changes enforced to prevent Cross-Site Forgery.
Source: https://blog.chromium.org/2019/10/developers-get-ready-for-new.html
I'm trying to set its value to "None" and use Secure as advertised.
My current web.config setting is as below:
<system.web>
<sessionState cookieless="UseCookies"
timeout="20"
cookieSameSite="None"
xdt:Transform="Replace"
xdt:Locator="Match(cookieless)"/>
</system.web>
Documentation Soure:
https://learn.microsoft.com/en-us/dotnet/api/system.web.configuration.sessionstatesection.cookiesamesite?view=netframework-4.8#System_Web_Configuration_SessionStateSection_CookieSameSite
But still I get the below error:
A cookie associated with a resource at `mywebsite.net` was set with `SameSite=None` but without `Secure`. A future release of Chrome will only deliver cookies marked `SameSite=None` if they are also marked `Secure`.
How do I specify secure attribute in the above web.config file ? Any leads will be much appreciated.
According to this link from Microsoft, sessionState doesn't have that attribute so it falls back to the httpCookies section.
https://learn.microsoft.com/en-us/aspnet/samesite/system-web-samesite
Hope that helps.
You can also set it per cookie creation
using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
....
context.HttpContext.Response.Cookies.Append(cookie.Key, cookie.Value,
new CookieOptions { SameSite = SameSiteMode.None,Secure = true });
I am a new ASP.NET Webforms developer and I am struggling right now with how to have and manage session timeout in my simple test application. Generally speaking, the test application is listing a number of items. The user can add whatever he wants to a shopping cart and when he clicks on Checkout, he will be asked to enter his information. There is no login or authentication. However, I am using session variables to pass the user information between different pages.
I need to have a timeout here in such a case that the user leaves the page for a long time. In this case, he should get a message and gets redirected to the home page or any other page.
How to do that?
I tried to do that by adding the following to the web.config file:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="60"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
cookieless="false"
timeout="60"
/>
I was trying to retrieve thousands of records from a web service according to the input parameters and naturally it was trowing timeout exceptions. I decided to put the following code in action to display a client-side message, so the user would change the input parameters to make the results more specific.
You can find this example in here.
Executes any code block:
public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
{
try
{
Task task = Task.Factory.StartNew(() => codeBlock());
task.Wait(timeSpan);
return task.IsCompleted;
}
catch (AggregateException ae)
{
throw ae.InnerExceptions[0];
}
}
For a specific amount of time:
bool Completed = ExecuteWithTimeLimit(TimeSpan.FromHours(1), () =>
{
/*your code block*/
});
After stopping the execution, you can redirect to the desired page.
First off I'd like to point you to this page here as it seems that:
You are using InProc mode, though providing state server information and timeout which does not make much sense.
There are different modes in this so most probably you only need
mode, timeout and cookieless items for InProc (which is the best choice for test applications)
Have you made sure that this is under system.web in web.config?
<configuration>
<system.web>
<sessionState mode="InProc"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web>
</configuration>
As an extra, your timeout is 60 minutes. Have you waited long enough? If the session is not set anymore you need to handle the redirect yourself.
Here is another SO page that might help you
By the way, if you are to use the in proc mode you can handle session expiry in global.asx
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
Response.Redirect("Add url here");
}
I want to add a "keep me logged in" option to my custom login control.
This is how I'm currently using the session:
I'm saving and reading values from HttpContext.Current.Session["key"] manually. Works fine.
Relevant parts of web.config:
<sessionState mode="StateServer" useHostingIdentity="true" cookieless="false" timeout="120" stateConnectionString="tcpip=127.0.0.1:42424" />
<authentication mode="Forms">
<forms loginUrl="/login" name="AuthCookie" timeout="120" slidingExpiration="true" path="/" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
As you can see, the default duration of a session is 120 minutes.
"Logout":
Session.Clear();
Session.Abandon();
Through a custom login control with textboxes, I grant access to a member area. (I don't use System.Web.Security.FormsAuthentication)
After entering valid credentials and a checked checkbox "keep logged in", I want to increase the duration of the already active session to ~30 days.
So far I've found solutions like
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddMinutes(1), false, "username");
string encTicket = FormsAuthentication.Encrypt(fat);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = fat.Expiration });
which don't work, because System.Web.Security.FormsAuthentication.Timeout is still at 120 minutes.
The same goes for setting
Session.Timeout = 666;
Any suggestions?
You can't really approach it this way. You can't persist a session over days - it's just not going to scale well.
What most people do is provide a means for automatic login, so that when their session expires, they are seamlessly logged back in on the next action/reload. Most people do this with a cookie that contains a unique hash, which is checked at the server. If you want the person to be logged in for 30 days, you just set the cookie to expire in 30 days time.
I decided to give a short summary how I ended up doing it, because #David Haney asked me to:
I added a column to my usertable, which contains a GUID that is used for "relogging in" / giving credentials again. That GUID is created upon login and stored in the database.
It's also stored as an ecrypted value in a cookie. (My site doesn't use SSL)
Added to Login routine (if a user checked the "remeber me" checkbox):
HttpCookie aCookie = new HttpCookie("Session");
Guid sessionGuid = // Buisiness layer call to generate value
String sessionID = sessionGuid.ToString();
aCookie.Value = Helper.Protect(sessionID, "sessionID");
aCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(aCookie);
where Helper.Protect and Helper.Unprotect are used from here How to use MachineKey.Protect for a cookie? to store an encrypted and MAC signed value in a cookie.
Relogging is done by having every content page inherit from a class, that implements that logic and inherits from System.Web.UI.Page.
public class BasePage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Request.Cookies["Session"] != null && !CustomIsLoggedInCheckMethod)
{
String unprotected = Helper.Unprotect(Request.Cookies["Session"].Value, "sessionID");
Guid sessionID = Guid.Parse(unprotected);
// Calls to buisiness layer to get the user, set sessions values et cetera
}
}
}
If a user was banned after the last session or logs out, the cookie value expiration date will be set to a date in the past:
HttpCookie myCookie = new HttpCookie("Session");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Edit:
Ah I forgot to mention this. I've also added a notification bar, that tells the user that he has been logged back in. It's based on http://blog.grio.com/2012/11/a-copypaste-ble-jquery-notification-bar.html
See Demo
Hello, I created a web site application with asp.net 4.5 and asp.net membership. I want user session to be expire if the user doesn't work with site (like Facebook).
I have set the timeout in web.config for the session but this time gets finished (times out), either if user works or doesn't work. Is there something I'm missing?
<authentication mode="Forms">
<forms loginUrl="~/Pages/Login.aspx" slidingExpiration="true" timeout="1"></forms>
</authentication>
While setting the forms auth cookie you need to set an expiry time for the cookie and create a http module in your application where you check the auth cookie in the request headers and if its not present you logout the user and redirect to the login page. And if the cookie exists just reset the expiry time for the cookie in the response.
Refer to this link. This is an answered that I'm currently help with another user. This should show you how to make the session start once the user logs in.
Edit: Not sure why the downvote, but here is code then.
Change the timeouts on each of the forms authentication and sessionState like below.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" defaultUrl="~/Dashboard.aspx" timeout="60"/>
</authentication>
<sessionState timeout="60" mode="InProc" cookieless="false" />
Then, put this into your Site.Master.cs under the page load.
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// Handle the session timeout
string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/DealLog/Account/SessionExpired.aspx";
StringBuilder script = new StringBuilder();
script.Append("function expireSession(){ \n");
script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl));
script.Append("} \n");
script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);
}
The session will only expire if the user is authenticated. The user logs in, becomes inactive, and then session times out. Once it times out, goes to an SessionExpired page. On the session expired page, place
FormsAuthentication.SignOut();
in the page load so it signs out the user. Then you can set up a redirect from there. The Authentication and SessionState timeouts are both in minutes. 60 = 1 hour.
Edit 2: It looks like the user of the question that was linked in my answer was deleted by the user. Sorry for that. Hope this helps though.
If I visit my site with out the www. prefix, login and then add the www., my user is not logged in any more, but if I remove the www., the user is logged in. It acts the same way if I do the Opposite. go to the web site with the www., login, and then remove the www. the user will not be logged in.
Here is the Login method and the authentication at the web.config.
public static void LogIn(userId)
{
Item user = Framework.Business.Item.Load(userId);
var _ticket = new FormsAuthenticationTicket(1, _usrItm.ID, DateTime.Now, DateTime.Now.AddDays(30), true, _usrItm.ID);
string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
}
<authentication mode="Forms">
<forms name="k_Authentication" protection="All" timeout="120" cookieless="UseCookies" loginUrl="default.aspx" path="/" defaultUrl="/myweb.aspx"/>
</authentication>
I'll bet you a shilling to a guinea that the two answers about the domain setting of the cookies are correct +1s all around from me.
However. Most often the two sites are the same or they are not. If they're not, then you usually want the user to no longer be logged in, so don't change anything. If they are the same, then set one to permanently redirect to the other. As well as making this problem go away, you also gain some SEO benefits, benefits for people's history records being more consistent, and reduced pressure on shared caches. So I'd suggest that approach. I'd only deal with the matter of the domain set on the cookie if the two are separate-but-related, and sharing the log-in between them is appropriate.
There is probably a problem with the domain of your cookie. www.example.com and example.com are not the same domain.
You'll have to set the Domain property to www.yourdomain.com manually to share the cookies.