ASP.NET Kill Session By Id - c#

My application has a control of User Permissions, because not all users can access full website. At this moment, all those permissions for an specific user are stored in his session, 'cause It would be a problem for me to search at Database every Post Back.
The problem is that when I remove a permission, user can still access the page, and only when he closes the browser, the update take effect.
Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?

"Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?"
No. You can only access the Session object of the user doing the current request (i.e. yourself), not other users Session objects.
So, you need to store the id of the user somewhere else, for example in a static collection. When the user makes the next request you can check if the id is in the collection, and update the permissions or log out the user.
Another alternative would be to keep the permission objects of all currently logged in users in a static collection as well as in their Session variable. That way you would be able to change the permission object without accessing the Session object of that user.
Using static variables in a web application of course comes with the usual precautions. As multiple threads can access it, the access has to be synchonised. Also, as Alexei Levenkov pointed out, if you have multiple servers you have to keep the data synchonised between the servers.

You can write Session.Abandon(); or Session.Clear();
or Session.SessionID[int index];
store the particular user session value in this and then use Session.Abandon(); and Session.Clear();
For killing a particular session try using Session.Remove("key");

To remove a particular piece of Session, then use Session.Remove(), like this:
Session.Remove("YourKey");
Note: This removes the value and the key from Session, while you may see people use Session["YourKey"] = null; that will only remove the value, but leave the key. This may or may not be what you want, but just wanted to point out the distinction.

Related

Can't determine if my asp.net session implementation is correct

I am very confused in my implementation of sessions in asp.net web application. My logic is once user enters user name+password, I validate credentials and then create a new session with some user info[All I am after from this point onward is that this user has access to restricted resources and a user must never be able to access those resources unless he/she is authenticated]. This I validate on each request and the rest. Here is my issue though. I have many places in the website where I have html links, and I read that if I have a link such as
<a href='resource1.aspx'>resource 1</a>
This will generate a new session id, hence in reality invalidating the existing session id, which in my case will be treated as session expired and user is sent to login page. While reading up on this issue I came across an asp.net API method[
Response.ApplyAppPathModifier(url);
] which prepends the session id to each request hence resolving the new session id generation for each link. Though it resolves session breaking issue it does add the session id next to all of the urls and now session id can be seen in the source code( view source for web page). I really don't want to use cookies and want to use session for user sessions...Can some one please help me create a system which will work the way I wish it to ? if I am doing it utterly incorrect, I would really really appreciate a details discussion and if possible some example...Thanks you much in advance..
It looks like you are trying to use cookieless sessions which add a session id to all links in order to be able to track the sessions.
The other (much more common, standard and IMO secure) approach is to use normal sessions, which auto creates a session cookie (when you use the .Session object), and uses that to determin the current session. If you don't want a cookie you'll have to stick with cookieless, and the session id in the url.

Show Log In user time details

I need to show user log in time details.I have two table.One is UserMaster which contains UserDetails and one is UserLogInTimeDetails contains two columns UserId and LogedInTime.
When User Log in UserId and LogInTime stores in UserLogInTimeDetails.
When User Log Off I am deleting the row of that particular user from UserLogInTimeDetails.
But the problem is if an user close the browser then the details of the user in not deleted from UserLogInTimeDetails table.For which that user will not be able to log in again.
How to solve this issue?
I have googled and saw that browser close event in not possible to handle and in many places they have adviced to use onbeforeunload event which is not working for me.
Please help. I am in big trouble.
Perhaps you could get it working using Session_End in your global.asax file to remove the user when their session expires. Though I'm not 100% sure if you can get the session ID from this method. It may be within the EventArgs...
void Session_End(Object sender, EventArgs e) {
//Remove user from database here
}
Else, another way to store the data is based on last activity, so everytime the user submits a request you update the time of last activity. You could even store this with a session ID in the database along with their login time, and then be able to calculate the duration active from login time to last activity for that session;
Best way to go with this using signalR. You can track user is online or offline. based on even dispose you can track exact logout or browser close too.
Hope this will teach you something new. refer below link for a simple example of signalR.
signalR sample application for online, offline status
Is it important that the user cannot login multiple times from different browsers?
If not, a more common approach is to store a login information variable in a session variable (maybe login time, user id or something like that), and use it to verify if the user has logged in or not.
If the user close the browser the session is lost, and he must login again, but he can login as many times as he wishes from different browsers.
You can access these variables like this:
// Set it like this. Can be any type of object with login data.
Session["LoginData"] = "Hello";
// Get it like this.
string test = (string)Session["LoginData"];
Edit:
If it is important that the user must nog login multiple times, you have a much bigger problem to solve.
Maybe something like this could be the solution?
Let the browser (via ajax) ping the web server somehow, every few seconds or so (how many depends on how long you want the browser to be shut down before it is ok to login again vs. traffic)
When the server receives a ping from a certain user, stamp the date and time in a session variable.
If a browser is trying to access the web page in any way, first, check for the session and for how long time ago the last ping was done. If the session is null, or the time is more than the time between pings*2 (or something like that) the user can login again (send to login page). If the time is shorter check if the user is logged in. If he is, continue. If not, tell him he must log out from the first connection (or whatever you want).
Hope this helps!

Duplicate Session ID

Hi I am working on Sessions and don't know whey the Session ID is created the same as the previous one.
I have a log table which tells which user has logged in, its time and stores its unique Session ID. When it log outs system checks for the Session ID n changes its status to log out.
But when user is logged in again the Session ID created is the same i don't know whats the mistake.
The Code is given below
log in cs file
HttpContext.Current.Session["user"]=user;
HttpContext.Current.Session["sessionid"]=HttpContext.Current.Session.SessionID;
when user log outs
log out cs file
HttpContext.Current.Session.Abandon();
Waiting for your help. Thanks in advance
You can use Guid.NewGuid().ToString() instead.
ASP.NET doesn't guarantee that the session id is unique beyond the lifetime of the session.
While each generated GUID is not guaranteed to be unique, the total number of unique keys >(2^128 or 3.4×10^38) is so large that the probability of the same number being generated twice >is very small. For example, consider the observable universe, which contains about 5×10^22 >stars; every star could then have 6.8×10^15 universally unique GUIDs.
You can always trust the GUID to be unique always. Thats the real purpose of GUID.
This SO Question asks about unique Id.
ASP.NET doesn't guarantee that the session id is unique beyond the lifetime of that session (ie. there's no living session with the same ID), I'm affraid. You should just use your own unique identifier if you want that functionality.
You can use GUID as suggested by Subin.
While time of creating sessions for a user, use the code below.
HttpContext.Current.Session["sessionid"]=Guid.NewGuid().ToString();
While Saving it to DB, use the reverse:
User.dbField = HttpContext.Current.Session["sessionid"]
Since the users are members on your website, they should already have a uniqueID, whether this is a email address or an Id? You can use this to make entries into the Login table.
Note: There is a caveat to this process; it will work fine if the user clicks on the logout button, you can remove the uniqueId from the Login Table or update status to logged out, whichever way you have this set up. But, if the user just closes the browser, no event will be fired to perform the same action, so the user will remain logged in.
You should also look at possible solutions for dealing with the clean up of users who have not clicked on the logout button.

Options for storing user information while logged in

What are some options in regards to maintaining user data while they are logged into my mvc4 site? I am building off of the Internet Application template and right now I am using User.Identity.Name to get the logged in user's username that they used to login with. I'd like to be able to also store and access several other pieces of information about the user across every page on the site. Can I still use User.Identity somehow and apply other attributes to it? I started building a ProfileModel that I could pass to views, but then I don't believe I would be able to pass other models to those views, not sure.
I'm open to suggestions as far as persistent user data, and thank you for any help.
EDIT 1: When I say persistent, I mean while they are logged in, the data itself is already stored in an external database, so I won't be doing any writing of this information, simply pulling it from the database, then holding onto it for the duration of them being logged in.
You'll want to leverage Session for that. Consider the following code:
Session["Profile"] = profileObj;
or maybe you just want to store a string:
Session["SomeSetting"] = value;
What you need to store in Session is unclear, and effectively irrelevant, you can store anything. You can access the Session from any Controller.
Then later on you can get the value out like this:
var profile = Session["Profile"];
// if the profile variable is null then it doesn't exist in Session yet
In response to #AaronLS, Session lasts the duration of the IIS session that's created when the user first accesses the site. Do keep in mind that these sessions are reset if inactive for a period of time (I believe the default IIS timeout is 20 minutes) so you'd want to leverage the null return value to know that you need to redirect the user to the login page to login again.

How to cache user's profile info (update when profile changed)?

I have a UserInfo object that is generated on each page_prerender event. This object is generated from the db and contains general info and permissions info. Since this object is always the same for each user - unless the user updates his profile - I'd like to cache it.
Does anyone know how I would do so per user (as each user of the web app has a different userinfo object) and get the new values into the cache when a profile is updated.
Any help is great! thanks!
Store the object as a session object in the session start event
this.Session["UserInfo"] = myUserInfo;
Update this object when the user updates there profile.
May be it worth to add issue a cookie for each user. If you will stop the application the session may be lost

Categories