session related question in asp.net - 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.

Related

Detect Session Expiry in Asp.Net MVC 5 Razor Application

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

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.

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.

What is the best way to show a message to user and redirect to home page when a session times out

I am currently working on a asp.net 3.5 web application which is being used by 500 + concurrent users and the session time-out is set to 24 hours but a recycling of ASPNet process on the server is scheduled to trigger everyday at 3:00 A.M. is causing the session gets timed out.
What is the best way to show a message to user and redirected to home page after session is expired? There are lot of pages in the project, so adding code to every page of the site is not really a good solution.
Thanks in advance
BB
You can use global.asax's session end event to perform your redirect & notification. Just a note, that the session doesn't end when the browser is closed. It ends when the session timeout reached.
void Session_End(Object sender, EventArgs E) {
// Clean up session resources
}

ASP.NET Webforms site using HTTPCookie with 100 year timeout times out after 20 minutes

I have a site that is using Forms Auth. The client does not want the site session to expire at all for users. In the login page codebehind, the following code is used:
// user passed validation
FormsAuthentication.Initialize();
// grab the user's roles out of the database
String strRole = AssignRoles(UserName.Text);
// creates forms auth ticket with expiration date of 100 years from now and make it persistent
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
UserName.Text, DateTime.Now,
DateTime.Now.AddYears(100), true, strRole,
FormsAuthentication.FormsCookiePath);
// create a cookie and throw the ticket in there, set expiration date to 100 years from now
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)) { Expires = DateTime.Now.AddYears(100) };
// add the cookie to the response queue
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
The web.config file auth section looks like this:
<authentication mode="Forms">
<forms name="APLOnlineCompliance" loginUrl="~/Login.aspx" defaultUrl="~/Course/CourseViewer.aspx" />
</authentication>
When I log into the site I do see the cookie correctly being sent to the browser and passed back up:
HttpFox output http://cid-e79f8e4b07c3e30f.office.live.com/embedphoto.aspx/Public/SessionProblem.png
However, when I walk away for 20 minutes or so, come back and try to do anything on the site, the login window reappears. This solution was working for a while on our servers - now it's back. The problem doesn't occur on my local dev box running Cassini in VS2008.
Any ideas on how to fix this?
Session timeout and Forms Authentication timeout are two separate things. Is the Session timeout set to 20 minutes, and would it be logging your users out in the Session_End event in Global.asax file by any chance?
By default, app pools in IIS 6 are set to shut down after 20 minutes of inactivity. If there's nothing in your app configuration that's causing your app to shut down that quickly, check the app pool configuration in the IIS Manager. There are lots of wonderful knobs you can set in there.
Well I do have the following in Global.asax:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null))
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))
{
FormsIdentity fi = (FormsIdentity) HttpContext.Current.User.Identity;
FormsAuthenticationTicket fat = fi.Ticket;
String[] astrRoles = fat.UserData.Split('|');
HttpContext.Current.User = new GenericPrincipal(fi, astrRoles);
}
}
}
}
Is that what you're referring to? Also, we're in an IIS6 environment if that makes any difference.
Another quick thing to check might be your hosting type. Cloud hosting will generally have a load balancer that is hard set to keep the same IP pointed to a node server for ~20mins, however after this time you might be pushed to a new server creating a new session on the new server and 'logging you out'
If your on standard shared hosting or a single dedicated server or virtual server however this won't be the problem :)
To get around this and keep the asp.net sessions working you need to move session state to a database - or re-tool your code to not use sessions at all :)
You might want to check whether you are using a load balancer. If so, then really you shouldn't be storing InProc. Should be looking into a state server or sql server if you have more than one entity.
Based on the issue, it seems that the default of 30 minutes isn't being adhered to either, which generally points to IIS/Hosting/Network configuration.

Resources