Limit user's asp.net session to 1 with WIF Secure Token Service - asp.net

We are building a set of web applications which all utilize their own unique role providers using sql server and utilizing Windows Identity Foundation to provide a Secure Token service to handle the membership using Active Directory. This solution also provides the benefit of single sign on. One oversight was only allowing users a single session. Tracking if the user already has an active session seems easy enough to implement, it’s what and how to deal with a user’s session if it’s determined they are already logged on elsewhere .
My question is what is the recommended approach for killing an existing user session if the user attempts to spawn an additional session? Would also like to advise the user that an existing session has been detected and by continuing, that existing session will be terminated. (This part also seems trivial…)
Example Scenario with 2 web apps and a STS Identity app:
User attempts to access application A:
STS Identity extension determines user is not already logged on, provides a claim and caches a user/session identifier.
User attempts to access application B on different computer. (they can access application B if using the same session)
STS Identity determines user has active session and denies logon.
There seem to be some other issuer to overcome, for example….
How to update the logged on user cache from the application A if the user is actively keeping their session alive.
How would you deal with the user not explicitly logging off, say by closing the browser or the session timing out.
Other problems???
Any guidance would be appreciated.

We have opted to handle concurrency at the application level, using a simple table that stores the users session id. If a new session for the application is created elsewhere, the existing session is terminated with the use being redirected back to the STS with a message (carried in the query string) the reason why they've been redirected back to the login page.

Related

Thinktecture Identity Server User Store

I am new to Identity server but I found it quite easy to set up.
Our goal is to implement SSO down the line but at the moment we are just moving our authentication logic out of application.
It is going good except I have one confusion.
When I set up the Idsrv, I had to create admin user as well as token requesting user. This was to access and configure Idsrv.
For application auth, I have to use Idsrv as federation server as well and authenticate users against some Asp.Net data store.
Now there is already one data store where Identity server specific users are stored.
Should I be using same store for my application user auth and created/edit these users in that store? Or can I/should I create a separate database for application specific users and use both?
At the minute, I am authenticating application users against Idsrv store.
I am not sure if I am logically thinking in right way to split these two user sets and calling one as Idsrv specific users. (We will have Identity service separately deployed for each application)
Thanks for your help in advance.

How does ASP.NET WebAPI using IIS store my users authentication state?

I have an asp.net Web Api 2 / Identity 2 application that requires a user to be authenticated. The authentication works but I notice that when I restart my local development machine and try to access a method that requires authentication then I get a failure.
As my application is unchanged from the asp.net sample then I think it uses cookies to store user data on the client. Where and how does the Server or IIS store information on which users have authenticated? Does it do this just the once or on every HTTP? Is there a difference between my using Token or cookie authentication in the way that the authentication and also authorization is checked on the server?
I think you are misunderstanding how authentication works with ASP.Net. As an example, let me show you some cookie details for a site of mine that uses Identity (note the token is actually in the cookie, the two are not mutually exclusive concepts):
Name __RequestVerificationToken
Value afeILhaIvRr56jXXXXXXXXXXX
Host site.azurewebsites.net
Path /
Expires At end of session
Note that the cookie, by default, expires at the end of your session. That means when you restart your development machine, your cookie is expired and your token is no longer valid.
In particular I have read that with token authentication then there is no need for continual re-authentication every time a request is made to the server
You need to understand that HTTP is a stateless protocol. Each request happens in a vacuum, and therefore you need to pass some data back to the server so that it can tell that the person who authenticated with Request A is really the initiator of Request B. Almost always, that piece of data is from a cookie. So, every request does indeed re-authenticate, and typically with a token in a cookie.
The only piece of data about your session that is stored on the client is the cookie (unless you are doing something atypical). The rest is on the server. How it is stored can vary:
Inproc: Easiest to setup, sessions are stored in process. So when your server or app pool is restarted, that data disappears
State Server Mode: Sessions are stored in process, but outside of the ASP.Net worker process, so the application can be restarted without losing session data
SQL Server: Unsurprisingly, this stores data in a database. Very resilient, but more work to setup. Also your best option if you are on a web farm.
ref: http://msdn.microsoft.com/en-us/library/vstudio/ms178586(v=vs.100).aspx
Expanding on the great answer by Chris, I would like to add that there are two possible models here. In forms authentication (which is the default membership type for asp.net) the cookie can either store authentication information and then it's called a ticket or the information can be stored in session, with the cookie being a simple identifier for "reconnecting" the authenticated session with the requesting client on each subsequent request.
This "reconnecting" happens in the Application_AuthenticateRequest method of the global.asax. If you are using the default forms authentication storage, i.e. an SQL DB created for you by the framework, the reconnection will be done automatically. If you are using a custom authentication store (like accessing active directory yourself or a custom users table structure) you can override the the method and reconnect the authenticated session using your own implementation. In any case, the authentication data is populated in the User.Identity object's different properties. From that point, if you use the [Authorize] attribute, the framework accesses the object to check if the user is indeed authenticated and authorized.
I any case, the authentication information is tied to both the cookie and the session. Assuming your session is InProc, like Chris said, when the session is lost (through timeout, app pool recycle or restart of the dev machine) the server-side of the session is lost and your authentication / session cookie is replaced by a new one on the next request.
EDIT: Ohh... and one more side comment. Make sure you distinguish between authentication and authorization. The client is not re-authenticated on each request. Authentication is the process of providing your credentials and being identified by the server. Authorization is, now that the server has verified who you are, on each request it checks if you are authorized to access the resource you are requesting.
The server doesn't store information about who's authenticated and who isn't. Depending on your authentication mechanism (forms, tokens?), typically, when a user logs in, the server will return some form of authentication token that the client should pass back to the server on each API call.
Without knowing more about your configuration, it's difficult to explain why when you restart your server you have to re-authenticate, it sounds like the authentication token generated by the server is invalidated on restart.
Where and how does the Server or IIS store information on which users have authenticated?
IIS does not store state based on cookie authentication. Everything is determined based on the request. Either a request has the correct encrypted information, or it doesn't. If you look at a default Forms authentication in ASP.NET, you will find a cookie called .ADUAUTH ... this cookie has all the information to authenticate the request. If the cookie is half expired, it will be reset, but that's all IIS does.
Does it do this just the once or on every HTTP?
Every HTTP request is unique, so yes, per HTTP request.
Is there a difference between my using Token or cookie authentication in the way that the authentication and also authorization is checked on the server?
It's always checked on the server: To find out more, check out: How ASP.NET Security Works: http://msdn.microsoft.com/en-us/library/ks310b8y.ASPX
I think my answer could be a little contradicting to all of the above.. But I think If I understand right..
IIS stores inside the memory space of the ASP.NET worker process, i.e the session data in the RAM.
The storing of authentication state depends on the authentication model you are using. For example: if you are using the Federated authentication, through ADFS, then when a user loads your web page he is required to sign in providing his credentials. The ADFS then sets the authentication token which is stored in the session data, the session id is stored as cookies in user's browser. The server has the mapping of Session Id to its session data.
Now the user is authenticated. The ADFS looks for authentication token to mark a user as authenticated.
When you restart the server, the session data is lost as the data is stored in RAM.
There are ways to handle this, there are 3 types of session storage:
1. InProc (Stored in memory space of ASP .NET Worker process - RAM)
2. State Server (Stored out side of ASP .NET worker process, like on cloud Azure storage)
3. SQL Server session storage (Stored in SQL server)
I think you are adopting 1, because of which you encounter the problem.
In cases 2 and 3, the session is not lost when you restart the server.
Several things --
Token based authentication is not really authentication. It is just issuing you a unique token (can be a guid, unique string, etc) and then associating it with something (like your IP address) and saving that association server side (in a database?). Now whenever you use that token, from the client app, the server checks the association already stored and serves or denies or request.
In many ways, it is very similar to using Cookies to maintain authentication. Only, token-auth was designed more for web services operation than for UIs.
In short: Out of the box, the membership provider will run it's authentication method and upon success, it will create an auth ticket/token/cookie that will be stored from the site. In addition to this, there is a session cookie that is stored with the site as well. When you make a page request, it'll pull these things and use them to determine whether or not you are already authenticated. If it finds the ticket and sees that it is still good, it'll allow access.
When you restart your local environment, the session and it's information is destroyed which is why you have to log in again.
There is an entire pipeline in the framework that makes all of this stuff happen (having to do with authentication, authorization, and identity) and there are number of ok articles on the interwebs explaining this, but imo, they're almost all incomplete or hard to follow. If you want a great soup-to-nuts explanation, PluralSight.com has some training videos that will deconstruct and explain the entire pipeline for you. Understanding the pipeline can help you implement your own custom authentication, and I highly recommend it.

Multiple site domains and virtual directory single login

I am creating a project which has a login portal with multiple applications and websites. I want to allow the user to login and then click any application and have access to it. Some considerations are: each application is defined in a user profile, ie which users can see what. also each application privileges are different for each user. so user a may be an administrator of application a but just a normal users in application b.
What i know.
I can have one auth cookie created in the main portal which with setting the machine key and same authcookie name, each application can use it. I have done a test with this and it seems to work.
My problem
As each site/ virtual directory has different privileges per user and per application when the user access a site i need to get his privileges from the databases but I cant then overwrite the auth cookie userdata with the new details because he may have multiple tabs etc open at a time on different sites. So how can i have an extra cookie store per user and per application for holding application specific details. I know I could go to the database each time but that's allot of overhead for each post back.
Maybe another option is to use the main authcooke for checking the user is logged in then have a new auth cookie per aplication and user, but how can i have 2 authcookies, that may get confusing and the second needs to timeout when the main one does et c i think
Any help suggestions would be gratefully appreciated
THanks
------------------- EDIT -----------------------------
we have one user table for all all sites not 1 per each site. then we map the user to an application and then the user application and role. so when you get to an application it has to check if the user has access and what there role is. all other user details are already in the auth cookie when loggedinto the main site. We do it this way because we have to manage users in one application not each application. Hope this helps understand my requirements.
What you are describing is a 'classic' SSO (single sign-on) example. There are lots of ways people have tried this and they are well documented on Google.
One way to do this is to have your SSO server (e.g. the first place you land and log in) to issue a security 'token' (e.g. a Guid) and then either store this in a cookie or append to URLs. Each subsequent call to an application can look-up the token in a database, verify it's validity and carry on (or boot the user out if invalid).
Using a database also allows you to set a timeout for all applications for which the token is valid.
This can then be extended to allow the database to store which apps each user can access etc. I've described this in very broad terms but it may be a good starting point.
Hope this helps
BTW: querying the database on each request isn't too much of an overhead. I have applications that do just that and are still performant when loaded with 300+ users.

ASP.NET MVC 4 and session security leak

Instead of using ASP.NET MVC User's system, I'm simply using session, as the following:
When he logs in (username + password), I fetch the corresponding user from the Database and set:
Session["UserId"] = fetchedUser.UserId;
Then, I'm always checking if he is logged in:
if (Session["UserId"] != null && ...)
The problem is that if someone copies the value of ASP.NET_SessionId from a logged in user (eg: user goes to bathroom and coworker who is sitten next to him checks his cookies with chrome inspector), then he will be able to create a cookie in his computer and act as that user.
My questions are:
Why are sessions safer than cookies if the session id is saved in a cookie?
Can I make this safer (and continue using session)?
How does internally ASP.NET User authetication system do it?
A primary reason for not using Session as an authentication mechanism is that it could render your application vulnerable to Session Fixation. For example, a problem could be if a user arrived on your site using the HTTP protocol and receives a session ID that is stored in the ASP.NET_SessionId cookie. The user may later log in, and even though your login pages might be secured under HTTPS the session token has already been generated under HTTP which means it has already been transported using cleartext.
To answer your other points:
Why are sessions safer than cookies if the session id is saved in a
cookie?
The data stored in session is stored server side, so it is more difficult for an attacker to tamper with this data. All the cookie stores is a token for this data, rather than the data itself. Having said that, it is still safer to use the FormsAuthenticationProvider as this creates a new authentication token once login is complete rather than on session start for the reasons of avoiding session fixation as above.
Can I make this safer (and continue using session)? How does
internally ASP.NET User authetication system do it?
The built in provider is already fit for purpose, so it would be desirable to use that rather than fudge another mechanism to meet your requirements. It is also easily extensible so you can customise it to your needs. The ASP.NET User Authentication creates an encrypted ticket and stores it in the cookie rather than storing a reference to a server side variable: http://support.microsoft.com/kb/910443
I would also draw your attention to the signout mechanism and how to secure it. Particularly
Calling the SignOut method only removes the forms authentication cookie. The Web server does not store valid and expired authentication tickets for later comparison. This makes your site vulnerable to a replay attack if a malicious user obtains a valid forms authentication cookie.
Details here: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.signout.aspx
In addition you may want to set the "secure" flag on your ASP auth cookie to prevent it being leaked over HTTP by a MITM attacker.

Keep User logged in across multiple applications on multiple servers

I am building a suite of applications using ASP.NET.
Each application can be hosted on separate servers.
All the applications share an integrated database.
All applications require user authentication before use.
I want to build the ability to transfer users from one application to another without having to relogin.
Is there a way to recognize that a user is logged in one application and allow quick navigation to another application on a different server?
Currently I am storing the password hashes in the database; but I wouldn't be opposed to other suggestions if they solve the problem.
Here is what I have done in the past.
Each application must share a forms authentication ticket. To do this the forms authentication cookie name must have the same name, the machineKeys must be the same, and the protection mode must be the same.
This works across domains, but does not work across IPs. What I do to get around this is to serialize the ticket info and store it in the database with the session id as the key. If a user is not authenticated the server will look for the session id in the database and rebuild the FA ticket if found.

Resources