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.
Related
Using Identity Serve 4 with .Net Core 3.1, razor pages. Also using Cookie Authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
Problem -
In a web application John logged-in 2 times
1st Login on Chrome
2nd Login on edge
So, if John again trying to logged-in on 3rd time on Firefox without logout from previous browsers, then I want to logout John from 1st Login on Chrome forcefully.
I can keep the track of logins in a Session table including Session Id, User Id etc.
But I don’t know how logout user from a particular session using Session Id.
Please help.
Thanks
ASP.NET Core provides an ITicketStore interface which allows you to get control of storing user sessions. Once you provide a class implementing this interface and register it, it will call your class when sessions are being created or verified which you can then store in a database however you like, including attaching arbitrary metadata like browser ID etc.
Now that you have user sessions in your database, you can separately query them and revoke as needed in other logic, including during logins. Since you now provide the session data, simply deleting the record effectively logs the user out from that session. Note that if you use any caching layer to reduce the store requests, you'd need to remove any cached copies as well.
Note that this is separate from IdentityServer and happens with ASP.NET Core itself.
This is a good tutorial that helped me implementing this in my app.
A sample of how it looks to register in Startup, where PersistentTicketStore is my implementation:
// Persistent ticket/cookie store to provide durable user sessions
services.AddSingleton<IUserSessionRepository, UserSessionRepository>();
services.AddSingleton<ITicketStore, PersistentTicketStore>();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Configure<ITicketStore>((options, store) => options.SessionStore = store);
Use the End Session Endpoint
The end session endpoint can be used to end a session and trigger a log out
In the log in process you will need to capture the id_token received from authentication and what user it belongs and store it on some dbo.table. You can use this same table to also keep track if a user has logged in more than once.
To log out a user or end a session you will need to pass the ID you saved as a query string parameter called id_token_hint in a GET call as shown below into:
GET /connect/endsession?id_token_hint={id_token}
For reference see the documentation here https://identityserver4.readthedocs.io/en/latest/endpoints/endsession.html#end-session-endpoint
Since you're saying you can keep track of logins, perhaps you should keep track of each session and assign a number somewhere indicating when it was logged in (1 for Chrome, 2 for edge, 3 for Firefox).
Then each time a request is made, you check in your table what the lowest number is (1,2,3 etc), and if the session matches that number, you sign the user out from that session.
await
HttpContext.SignOutAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme);
Since each browser will have their own cookie, you can use the above method.
After signing someone out, the next login can be assigned 4, and if 2 makes a request you log that client out.....
Also see this: https://github.com/IdentityServer/IdentityServer4/issues/736
I have implemented this.
When a user logs in, the session id (IUserSession.GetSessionIdAsync) is manually stored in our database. The previous value of this database field is used to create a logout_token which I send to my clients. You can have look at IdentityServer4.Infrastructure.BackChannelLogoutClient to figure out how to create the token and post.
All this assumes you have backchannel logout implemented ofcourse.
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!
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.
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.
Before I start I would like to state that I am very VERY new to ASP.NET and C#, and programming in general really. I have created a web application with a login page looking to a custom database containing the user's data as well as their login details. I did this rather than using the ASP.NET Membership as there are complications using this over my college's network.
As the table contains many records of user data, what I would like to do is have a user log into the app and (based on their login details) allow them to view JUST their details from the table I have created as their are many records of user data.
Am I correct that I should create a session based on their username and password and with this, somehow match it to their record in the table using SQL which will display ONLY their data rather than the whole table be displayed?
If this is the case, I really don't have a clue how to implement this.
I am aware that this will be very insecure but the users are all fictional and this app will not be published to the web. I just want it to work in the simplest form for my assignment and I'll cover the security aspects in my report and state how it could be improved.
Any advice would be greatly appreciated, Cheers.
Whenever you find a user's credentials valid enough for login, add some/all of his credentials to the current session like,
Session.Add("sessionvariablename",textBoxLogin.Text);
On the other page, that comes after logging in, check the following,
if(Session["sessionvariablename"].ToString()=="xyz")
{
Do whatever you want
}
You may not want to add sensitive information to the session for security concerns. Use
Guid.NewGuid() to create a unique 32 character hexadecimal code for each user and store it in session.
You should have row in your table with with a unique identifier. Like ID or userNr or something similar, make it an integer and set to primary key and then set its identity specification (is identity) to yes by double clicking on it (I am presuming that you are using visual studio).
When the user has submitted there login info and they checked out, you save there unique identifier in a session.
when you need to pull out information specific to the user in question, you use sql WHERE ID (or userNr) is equal to the session id.
hope this is what you needed, its my first answer in here so I would like to be helpful.
If I'm getting it right, using username and password as session parameters will work but it's not the best idea. Normally you table with users contains a kind of unique identifier for each record (guid or autoincrement id). You may use this identifier as a session parameter.