How to check if signed in user has timed out in DNN - c#

I don't know why this is so difficult, but I want to be able to do something (in my DNN module) in the event that a login has timed out due to inactivity.
I have tried checking Request.IsAuthenticated, and HttpContext.Current.User.Identity.IsAuthenticated, and even the Dnn UserId but these don't seem to reflect the event where a user has been logged out (both IsAuthenticated properties are always true, and the UserId is what it was for the user).
Any ideas on this?
Thanks
Edit:
According to some information, it should be as simple as checking UserId (if it is -1, it means that the user is no longer signed in) however it always comes back as the user's original ID, which is frustrating.

I found this excerpt from DNN Forum site on Sessions Timeout:
we don't use sessions, what you describe is authentication cookie timeouts - these are controlled via the forms timeout value in web.config. However I recommend you consider using persistentcookietimeout http://www.dotnetnuke.com/Resources/Wiki/Page/PersistentCookieTimeout.aspx , though if you don't want to support persistent cooies you can disable the remember me function http://www.dotnetnuke.com/Resources/Wiki/Page/Disabling-support-for-persistent-cookies.aspx

Related

Identity isAuthenticated cookie

I have a question regarding ASP.NET Identity provider.
I have made a system where you can execute CRUD operations on users and roles, though I have encountered a problem. If I was to delete a user which is already authenticated (signed in) he will still be able to perform actions on the site as he still keeps the authentication and authorization cookie on his local machine. When the user logs out he is no longer able to access the site.
My question:
Is there a way to make it so when a page is requested it checks whether the user exists in the database or not? Another way could be to not store 'role' cookies and check (via the database) if the user has the required role to access the page or not. I'm not sure how to configure this. Any help is appreciated.
We added the SecurityStampValidator specifically for this scenario, basically you configure the CookieMiddleware to check that the user is still valid every so often.
See this question: What is the SecurityStamp
I believe that if you set cacheRolesInCookie="false" in your web.config on the <roleManager> tag you'll get the desired effect. You'll then be able to handle the user no longer being present in the db and redirect the (ex) user as desired.
I found that installing and reading through Microsoft ASP.NET Identity Samples 2.0.0-beta2 found here: https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples in combination with reading this: https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/SingleSignOutSample/ was very helpful in solving my problem.

MVC4 Simple Membership When Does Automatic Login Occur?

I've got an application that's using the MVC4 Simple Membership provider. I've added some code to the Login method that sets up some session information I need to deal with some security things.
If I close the browser and come back to it, MVC still shows me logged in in the top left corner and the User.Username properties are still filled out, but the extra stuff I put in there, obviously, isn't.
When or where does this "authentication" take place? I tried checking the request and user objects in the Application_Start in Global.asax, but they're still null when that runs.
Is there somewhere else in that authentication pipeline that I can override or call my method to extract the things I need that would be more appropriate?
Thanks!
"Remember me" functionality has nothing to do with Simple Membership, or any membership. And no actual "login" occurs when using it. It's a persistent cookie that is placed on the users system, and that cookie is read when a page is loaded. If it contains the correctly encrypted data, then the user is considered authenticated without having to go through Membership validation again.
What you need to do depends on how you are doing it. If you're storing data in the session, this is bad regardless, because the session can be reset at any time, and session is not connected to authentication. What you need to do, is check to see if the data you need is in the session, and if not, rebuild it. This way it works when you come back later, or if your session is reset.
Session probably shouldn't be used anyways, because it doesn't scale well. A better choice would be to hook into the OnAuthorization method of the Controller class and do what you need there, that way it's done on every page request regardless of what the session may or may not be.
Another option is to create a custom AuthorizationFilter.

Allow only one concurrent login per user in ASP.NET

Is it possible to allow only one concurrent login per user in ASP.NET web application?
I am working on a web application in which I want to make sure that the website allows only one login per user at a time. How to check that the current user already logged in or not?
Please suggest proper login method by which we can handle this problem. I think we should use SQL Server session state to handle this problem. What do you suggest?
I thought of one solution for it. We can do something like:
When the user logs into the system then we insert session id in user column. (We will use database session so that we can get all session related data like isexpired, expiredatetime etc easily).
When the same user tries to login a second time then we will check for that session id column and check that session is already expired or not. If session is not expired then we will not allow user to login.
Update user session ID every time when user logs out.
Please suggest whether this is the proper way or not.
Please refer to:
When the same user ID is trying to log in on multiple devices, how do I kill the session on the other device?
Out of the box, .NET does not support this. .NET allows for concurrent log-ins, as I'm sure you're aware.
I had this same exact requirement, and came up with a pretty slick solution, demonstrated in the link above. In a nutshell, my requirement was to only have one user log-in happening at one time. If that same user ID tried to log in elsewhere, then it killed the session for the first log-in by checking for an existing log-in under a different Session ID (this enabled the user ID to be logged in from multiple instances of their web browser on their computer [same Session ID], which is common, but not from a different computer [different Session ID] (possibly due to someone that stole their credentials, for example)). Through modification of the code you could probably change the behavior of this - i.e., prevent the second log-in attempt instead of killing the first log-in that's already active and in use.
Of course, it may not fit 100% to what you're needing, so feel free to modify it to fit your needs.
You can create a cache entry per user and store their session ID in it. Session ID will be unique per browser session. In your login page, you can create that cache entry when they successfully login:
if(Cache.ContainsKey["Login_" + username])
// Handle "Another session exists" case here
else
Cache.Add("Login_" + username, this.Session.SessionID);
(Code typed in textbox without syntax check. Assume "pseudo-code".)
In global.asax you can then hook into the Session_End and expire that cache entry of the user. See this for the global.asax events.
if(Cache.ContainsKey["Login_" + username])
Cache.Remove("Login_" + username);
You could add a flag column in the user table that indicates that a user is currently logged in.
When a users attempts to log in you check the flag if it's true (that users account is already currently used) then you don't allow the new user to log in, if the flag is false the users is allowed to log in as there account is not being used by anyone else at this time.
Be aware though that unless the uses actively logs out, you cannot know when the users moves on to something else (goes to different website or closes the browser, etc.) so you need to set some kind of session timeout that will automatically log out the user if there are no new requests within a specified time period.
This means that if a users closes his/her browser and try to log in on a mobile device for example, he/she will be unable to log in until your specified session timeout runs out, so give the timeout a bit of thought as you don't want the user to get logged out to quickly (if he/she is reading a long page, etc.) and you don't want the users to be unable to log in on another device for hours if he/she forgot to log out before leaving the home.
The login credentials are stored on the cookie, so to know if the user is logged in you need to keep this informations on server, prefered on a database because the database can be the only common place among web garden or web farm.
What you can keep, is on a table, that the user A is logged in or not, flag it that is logged out, maybe last user interaction to have a timeout, etc...
So let say that the User A, is logged in, then you open a flag on the database for that user, that is now logged in, and if is try to logged again, you keep him out.
To make this work you need to either say to your users to log out, or to keep a time out, similar to the time out of the credentials.
If You are using identity system this link will help you how to single user login on multiple device.
Prevent Multiple Logins in Asp.Net Identity
I have tried they work fine in my Asp.net Mvc Project.
Solution can be this way:
Add new column in your login table GuidCode.
Step 1 : When logging in check if the GuidCode in database is null.
Step 2 : Update GuidCode by new guid and also store it in the session.
Step 3 : If it is not null then take guid from the session and compare with database GuidCode value.
Step 4 : If it is same then allow login:

Session is not expiring?

Probably my question is stupid but it is driving me crazy, you see I have this application its session is not expiring after logging out even though I have used Session.Abandon(), Session.Clear(), and Session.Removeall(). I have been searching all over the internet but no luck so far and I really wish I can get some help. Say I have user X if I do the following any one can login with X's account:
1- Login with X's username and password.
2- Take Session ".ASPXFORMSAUTH" info.
3- Logout from X's account
4- Add the Session ".ASPXFORMSAUTH" with its value using fire fox "add cookie function" for example.
5- type the URL and click enter
the page just opens up and it is really driving me CRAZY!!
Thanks in advance
You also need to call FormsAuthentication.SignOut()
In this case, you have an additional flag in Session (like "ACtive") which can be set to false during logout. Based on this, you can rediect the user to login or any other general page you want to..
I am not sure if there is defined way to handle this, but I would do something like I said.
Scenario where the user is already logged out by using FormsAuthentication.Signout() and is trying to hack the system by using the same cookie (he somehow got access to it) to access a authenticated part of the website.
In such a scenario recommendations from Microsoft also suggests to use a persistence mechanism to log / track the user signout and use the information to redirect him to login page (and clear cookie again) in subsequent fake requests.
Reference: Read bulleted point 3 in Remarks section

creating global session

i want to create a global session which will stay active until and unless we manually kill it. how to do this in asp.net with c#
what i am doing is
HttpContext.Current.Session["UserID"] = someValue;
but in this way the session is lost after some time.
You can set the timeout in web.config under system.web -> sessionState -> timeout. Not sure if you can have an infinite session though.
Also, you might be interested in the Application object which stores things in the "application's session" instead of the user's. Comes to my mind because you speak of a "global" session.
What's the application for this? Sounds like you're actually trying to use the session as a persistent storage, which will however only seemingly work even if you manage to set timeout to never or 5 years or whatever - because sessions will be "timed out" once the application is restarted. You might still get around that, but you might be better off looking for real persistence solution like a database. I may be totally off guessing your application for that of course.
Store the data in the Application state rather. It will stay there till you remove it, or the app dies/recycles/ends.
Usage:
HttpContext.Current.Application["Foo"] = "bar";
As nicolas78 says use session timeout configuration property to control the session expiry after user inactivity. In case, you are facing a requirement where session should be active as long as browser is open, there are two ways -
Use cookie to store some token and then re-construct your session state using the token if session gets expired. For example, user details can be recovered from user store if user id is stored in token. At worst, you may have to move your entire state to the database.
Keep the ASP.NET session state but keep it alive by firing AJAX requests from browser. I would suggest to fire such request after n/3 interval where n is your session timeout (ensuring at least three requests are made so even if two gets lost or falls on edges, one gets through).
Perhaps you're after profiles?
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
Profiles live beyond the session and are usually used to store per-user settings that the user can edit, such as their contact details and application preferences.
Profiles can be used with both anonymous and authenticated users. When an anonymous user signs in, their anonymous profile can be migrated into an authenticated profile (i.e. one that is attached to their user name).
Good walkthrough here: http://quickstarts.asp.net/quickstartv20/aspnet/doc/profile/default.aspx

Categories

Resources