Identity isAuthenticated cookie - c#

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.

Related

ASP.NET MVC SQL Server not accesable when trying to authenticate or access roles?

When I try to use Roles.IsUserInRole("roleX") or any related method I get a database connection issue, as can be seen here. I can access roles in the database and read/write any time before this, so I am quite sure I do not have any connection issues. All users role ID's match fine. The error also happens when trying to access a controller method that is authenticated to a certain role? Once any line relating to role checking is hit the app instantly locks up and errors out after about a minute. The only time I ever get this error is when trying to access roles, not sure if somehow identity is not connecting to the DB? I am at a total loss on this issue, the only thing I can think of is that something with Identity is not set up right. Any ideas are greatly appreciated.
Your problem is that Roles.IsUserInRole("roleX") is not part of Identity framework. This is part of MembershipProvider and you don't want to use it. Reason for getting this error - MembershipProvider tries to be helpful and attempts connecting to a database, a database you never told it about.
If you need to check if current user is in a role use User.IsInRole("RoleX");. Where User is part of a Controller or a View. Or you can also do it via HttpContext.Current.User.IsInRole("RoleX"); This checks the auth cookie for information about roles (all the roles for logged in user are persisted in auth cookie).
If you would like to dip into database to check for roles for an arbitrary user (not the currently logged in one) - you need to use ApplicationUserManager.IsInRoleAsync()

How to check if signed in user has timed out in DNN

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

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:

ASP.NET single page authorization

I have an ASP.NET application where most of the pages are accessible to all authenticated users via a single sign on module that sets the username into the Session array variable. Now I have one folder A containing one page B.aspx and a list of usernames who are allowed to access this page B.aspx.
My question: how do I elegantly authorize only these users for this one page, or better, for this one folder. Can it be done with the location tag in a Web.config file inside folder A ? If so, how do I connect that config with custom code to check whether the username stored in the session variable is one of the authorized for that folder or page ? Can I use a custom membershipprovider ?
Thanks in advance !
First, you scrap the kludged security methodology, as user name in a session cookie is not a good way to handle this. Okay, maybe a bit too overboard, as low security may be fine for you. If so, you can write a custom handler for the page that examines user name and compares to an updateable list.
NEW: With Session object, you are a bit more security, as the session token is sent over and the name is kept in session, but the Membership bits (below) handle translation of a particular session to a user without rewriting with your custom "this user is using this session" methodology. Yeah, ultimately you can argue Microsoft does something very similar to your software, but you leave the maintenance to them.
Going back to my original direction, there is the concept of roles and membership built into ASP.NET. If you use these bits, you can security trim the page (or even better folder so you can additional pages) to certain users (not as good) or roles (better) by setting up a new web.config with the security constraints.
The cool thing about the built in stuff is you can declaratively set up security and have the pipeline determine whether a user is valid or not without any heavy lifting on your part.
There is plenty of information on Membership and Roles on the various ASP.NET oriented sites.
that can be achieved specifying the user's name that can access the directory separate by commas.
As your username is not defined in web.config rather defined in some session variable you have to create a Form Authentication Ticket for this e.g.
FormsAuthenticationSupport formsAuthenticationSupport = new FormsAuthenticationSupport();
formsAuthenticationSupport.SignIn(UsernameInSession, RoleName, true);
Now you can set authentication rules and location tag in web.config for UsernameInSession.

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

Categories

Resources