Logging out User from one System if logged in another System - c#

I have a web application where user first log in to view the pages. My task on which I am is stuck is as follows.
If User is logged in from System A and does not log out, and he then logs in from System B, how can I make sure that the User is logged out from System A when he log ins from System B?
What adjustments do I have to made in my Data Base. I have log table which keep the records when user log in.
Is this possible?

Just log his IP address when he logs in - if the current IP is different from the stored IP, log him out of the stored ID.

You are not telling much about the structure. But I guess you have a "User" table.
In there you could have a Session ID, and if that changes, then you have logged in, in another place. So if you are logged in to "System A", you get a SessionID, which you check up against every call or every now and then.
Then you log into "System B", a new Session ID is created, and applied to the User table.
"System A" will then at some point look it up, and see that it is not the same as the one it knows about, and tells the user to log in again, or just simply forces a log out.

Easiest way I can think of will be -
1) After a user successfully logins, system creates a Guid and saves it inside user's SessionState as well as in user's table.
2) When the user requests a page, compare the user's SessionState value with the one from user's table.
3) If not same, redirect to Login page.

Related

ASP.NET Identity Concurrent Logins

I have an ASP.NET Web Forms application. This application is not something that will be used internally, but rather will get installed on a server and sold to customers who will use it internally.
So with that, we have limited the number of users that can access it (different packages: 10, 25, 50, or unlimited). The problem is, however, that with ASP.NET Identity, concurrent logins are allowed. This means if a customer has a 10-user system, they could all log in as the same user, and have effectively unlimited user access. So if "Dave" logged in as Dave, then Jim could log in as Dave, as could Bob, John, Stacey, and any number of people.
What I'm missing is a way to force concurrent logins to logout, if the same user. So if Bob tries to log in as Dave, then Dave (the original login) gets logged out.
I found a couple of examples that somewhat work around the issue, but they were a little dated, and were for MVC.
I was able to solve the issue by utilizing cookie authentication and an asynchronous method to update the security stamp.
Basically, the user's login information is stored in a cookie, which gets validated on every page load. When someone else logs in with the same username (or the same user logs in with a different browser), it updates the security stamp (causing invalidation for anyone currently logged in) and then proceeds to log the user in, using the updated stamp. On the login screen, my "Login" button's LogIn event is:
protected async void LogIn(object sender, EventArgs e)
Then below in the body of the method, we have:
await signinManager.UserManager.UpdateSecurityStampAsync(user.Id);
await signinManager.PasswordSignInAsync(Username.Text, Password.Text, true, false);
Response.Redirect("~/Default.aspx");
This will ensure that every time a user logs in, their SecurityStamp is updated and stored in the database. And as long as the user goes back to the site in the same browser, then their login will be persisted. However, if any user comes behind them in a different browser and logs in using their same credentials, then the first account will be logged out.

Restrict concurrent login - ASP.NET Identity

I am trying to only allow a user account to be logged in, only once at the same time.
E.g. User logs in via the browser on their computer, now they cant login at the same time on their phone as they are already logged in.
I can add a bool property to my user entity, that I can update when the user logs in and logs out.
However, I am using SlidingExpiration on the authentication cookie, therefore when the cookie expires it doesn't update my user property to say they are now logged out.
ExpireTimeSpan = <time period>,
SlidingExpiration = true,
Are there any better approach to restricting concurrent login?
Thanks
Can you generate a Token at log in and store it in Data base?
Then, check every time if the token matches with the one provided by user.
If he does log in in another device, the token will be overwritten and won't match with the first one, so the first session will become invalid.
EDIT:
As you asked in a comment, it doesn't block a user to perform a second log in in another device concurrently, it only invalidates the previous sessions.
Avoiding a second log in requires more job and isn't as safe as the method shown above.
Imagine that the user closes the browser without performing a log out... It will block the session.
An approximation of what you want will be adding the time parameter to your log in (adding it into the data base too, and updating the field on every user's action).
Then show the message of "you can't log in twice" if the token doesn't matches and the time span is not far enough (i.e. 5 minutes). But in my example you need to show a "your session expired" if the token has changed anyway.
"The idea is very simple every time the user logged in you have to generate random token , then you should save that token in the database and in session or if you are using Microsoft form authentication you can save it in the ticket, then each time the user request a page you’ll check if the session token is same as database token , if not kick him out!"
http://engthunder.wordpress.com/2011/10/19/preventing-multiple-user-from-logging-in-using-the-same-username-single-user-login-at-a-time/

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.

Categories