Detect Session Expiry in Asp.Net MVC 5 Razor Application - asp.net

I am developing Asp.Net MVC 5 Razor Application. I am maintaining separate table to maintain login information. When user logs in, I put 'true' in a field (IsLoggedIn) on success callback of login, in that table. When user logs out, I put 'false' in that field on success callback of logout module.
I am having one problem. If user does not press log out button, and its session is expired it gets log out. My success callback of logout is not called and 'IsLoggedIn' field in database still shows true for that user.
I am unable to find anything regarding how can I detect session expiry event and call my table updation function to put 'false' in 'IsLoggedIn' field to for user row?
Any Help?

Session timeouts can be handled in the Session_End event in your Global.asax, if your application using InProc SessionState mode(this is default in ASP.net if not specified)
void Session_End(object sender, EventArgs e) {
// perform your logic
}
before doing this remember one thing The event will be called, but not necessarily right after the timeout.
also take this into consideration that According to MSDN,the HttpSessionState.Timeout property has a setter and can be changed from within your application's code as well as permanently in the web.config
Hope this helps

Related

Session Log Out Issue

There is web application which is created on asp.net.
This application works perfectly when i run this on my local.
I have used session to store the userId of the user in the session.
In every page where i want only logged in user to be able to enter i have written code like.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["userID"] == null)
{
Response.Redirect("login.aspx");
}
}
}
So when session does not have userID user gets automatically redirected to login page.
I am facing two problems
1.When I deploy it to BigRock shared server.User automatically gets logged out in 5 minutes.It is defined session time out set in that server which I can not change. I do not want my user to get logged out automatically.
2.Payment Gateway is also integrated with this website and when the user clicks on check out .He gets redirected to payment gateway but when after entering his payment details and transaction completes when he gets back to response page ,he again automatically gets logged out whether 5 minutes was completed or not.This also works fine when I test this for the condition when I run this website on my local.
Every help is appreciated.Thank You So much in advanced!
Please let me know if you need any more clarification or source code.
Well, you can always try logging back the user based on the order-id received from PG. Since the response from PG is usually protected by checksum, you can rely on it's authenticity to carry back the user to your page. Just update your login session by using FormsAuthentication.SetAuthCookie method to re-login the user.
In your case since your directly assigning userdId to Session (IMHO, not the best way to manage logins though. Try searching for MembershipProvider), the steps are pretty straight forward.
Get the OrderId from PG response.
Fetch the associated userId from Orders table (For this you must have associated each user with their orders.
Save the userId in Session.
Redirect the user to secure page.
Why are we not asking for password? Because, responses from PG are usually protected by means of hashing and usually immune to tampering. So you can safely bet on the authenticity of the user redirected by PG.

Why isn't ViewStateUserKey enabled by default

ViewStateUserKey seems like a very useful feature to prevent some CSRF attacks. Why is it not enabled by default in asp.net applications?
I tell some thoughts about:
The ViewStateUserKey can break the viewstate in a valid user and as result a valid user see an error. So its better to let it out, and only advanced programmers use it and know why the view state is break and handle it if possible.
Lets give you some examples.
If you use it as it is:
void Page_Init (Object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
ViewStateUserKey = User.Identity.Name;
}
and see this steps.
a valid logged in user see a GridView on a page that is not require
logging.
this user have left the page some time, and the logging is
expired
now is try to paging the gridview, and gets a viewstate break
Why, because is start the page using the ViewStateUserKey, but after is expired the ViewStateUserKey is now different (null because the user is not logged in now) and break the viewstate and at the same time this page is not required to be logged in, and not redirection is happens to ask for logging again.
With this simple example, that is really happened to me, I say that this parameter can break the view state and if this set by default is may lead to some issues like that.
relative:
ViewStateUserKey + shared hosting + ViewStateMac validation failure
http://www.hanselman.com/blog/ViewStateUserKeyMakesViewStateMoreTamperresistant.aspx
http://msdn.microsoft.com/en-us/library/ms972969.aspx
Conclusion from experience.
If you use this key for any page that is not request login, and you are just in other pages logged in, this can easy create viewstate error on post back and break the page, and the post back. So you can not have it enable by default - and the one that use it must know this case I describe above.

How to access value from code behind in global asax

In my page I'm regenerating session id on every button click to go to the next page. I've already saved username in my session variable (session["uname"]=txtusername.text) in the time of log in. But as I'm regenerating new session id ,session["uname"] is having null reference because of new session id.That's why I want to set the session variable value using a Global.asax in session start function.
void Session_Start(object sender, EventArgs e)
{
session["uname"]=here;
}
But here in Global.asax page I'm unable access any value from my log in page..
The main problem is accessing any value in global.asax from code behind.
How can I solve this......Plz help......Thanking in advance..............
HttpContext.Current.Session["uname"]=here;
First don`t write business logic in Global.asax .
I want to point you out 3 basic things:
When session_start() called
How sessions are maintained
Where you should set your session variables.
For the following details I am assuming you have login.aspx, login.aspx.cs:
As you know HTTP is stateless protocol, so every request is new request.
So for every request session_start() will get executed.
When user request the resource for the first ever time, unique session will be generated, and cookie containing session Id will be sent to client.
For any further request from the user, HTTP client will pass the cookie to server, so user can be tracked by the server. This is how session works.
Now lets come to your code you are setting Session["uname"] in session_start() of Gloabl.asax, keep in mind that Globlax.asax is called before the page life-cycle begins
so it does not have access to page data.
Instade you should set your Session["uname"] in login.aspx.cs file. Here check if users credentials are correct then:
set Session["uname"]=value.
Now for every other request Session["uname"] for that user will be available. And you can also retrieve/update the values at session_start() of Global.asax too.

session related question in asp.net

1) re-login in asp.net
In my application,I do not want two user login with the same login name.
For example, user1 login with name "test1",then user2 try to login with "test1" too,but at this moment the user1's session does not expire,so the login of user2 should be denied.
No my question is how to check if the user1's session is expire or not when user2 try to login?
2)the timeout property of formauthentication VS seesionstate
what is the difference?
I have googled,but I am not sure how to use them.
it seems that the session have some realationship with the cookie,so when a session come to the server side,sometime we have to check if this session is a new session or not,I wonder when we have to check this?
3) Global.asax
There is a method:
Application_Start(object sender, EventArgs e)
What does the application start mean? the iis?
To get all user session here is a tutorial with code.
http://weblogs.asp.net/imranbaloch/archive/2010/04/05/reading-all-users-session.aspx
formauthentication VS seesionstate
I think that this is very clear, you have 2 different variables. The formauthentication says how many times keeps you login, and the sessionstate says how many times keeps your session data. The asp.net keeps 2 different cookies to connect a user with the authentication and with the session and the expires is referred to this cookies on the user computer.
it seems that the session have some
realationship with the cookie
Of cource he has, how else the server can make relation of the session data with the specific user ? using cookies. You need to check for new session every time the session is null !
The
Application_Start(object sender, EventArgs e)
fires when your application starts.
For example, when you open the appoffline.htm, your app stops, when you close it your app starts again, when the pool of your application make a restart because of the settings, when you upload new files and your applications make a restart for after the compile, and when you make a restart from iis, and of course when you restart your iis, or when you computers boot.

Avoid losing PostBack user input after Auth Session has timed out in ASP.NET

I have a form that sits behind ASP.NET forms authentication. So far, the implementation follows a typical "out of the box" type configuration.
One page allows users to post messages. If the user sits on that page for a long time to compose the message, it may run past the auth session expiration. In that case, the post does not get recorded... they are just redirected to the login page.
What approach should I take to prevent the frustrating event of a long message being lost?
Obviously I could just make the auth session really long, but there are other factors in the system which discourage that approach. Is there a way I could make an exception for this particular page so that it will never redirect to the Login so long as its a postback?
My coworker came up with a general solution to this kind of problem using an HttpModule.
Keep in mind he decided to to handle his own authentication in this particular application.
Here goes:
He created an HttpModule that detected when a user was no longer logged in. If the user was no longer logged in he took the ViewState of that page along with all the form variables and stored it into a collection. After that the user gets redirected to the login page with the form variables of the previous page and the ViewState information encoded in a hidden field.
After the user successfully reauthenticates, there is a check for the hidden field. If that hidden field is available, a HTML form is populated with the old post's form variables and viewstate. Javascript was then used auto submit this form to the server.
See this related question, where the answers are all pretty much themes on the same concept of keeping values around after login:
Login page POSTS username, password, and previous POST variables to referring page. Referring page logs in user and performs action.
Login page writes out the form variables and Javascript submits to the referring page after successful login
AJAX login
If you don't care if they're logged in or not when they POST (seems a little iffy security-wise to me...) then hooking HttpContext.PostAuthenticateRequest in an IHttpModule would give you a chance to relogin using FormsAuthentication.SetAuthCookie. The FormsAuthenticationModule.Authenticate event could be used similarly by setting an HttpContext.User:
// Global.asax
void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) {
// check for postback somehow
if (Request.Url == "MyPage.aspx" && Request.Form["MySuperSecret"] == "123") {
e.User = new GenericPrincipal(new GenericIdentity(), new string[] { });
}
}
When the session timeout happens the user's session (and page information) get disposed, which would mean the eventual postback would fail. As the others have suggested there are some work arounds, but they all assume you don't care about authentication and security on that particular page.
I would recommend using Ajax to post back silently every 10 mins or so to keep it alive, or increase the timeout of the session as you suggest. You could try to make a page specific section in your web config and include in there a longer timeout.
I handled this once by adding the form value to the database, identified by the remote IP instead of user ID.
( HttpContext.Request.UserHostAddress )
Then, after login, you can check to see if the current user's IP address has a row in the database, and perform the required action.
Michael

Resources