ASP MVC 3: Authentication lost sometimes in production - asp.net

I am developing a web app using MVC 3 that is using standard form authentication. It is hosted on a shared hosting. The problem is that sometimes the user authentication state is lost. I get no exception at all. Do you have any clue what can be the cause?
Does authentication has anything to do with session? I am not using Session object at all.
I was of the impression that Authentication using cookie can work in a load balanced environment. Am I wrong?
The session is lost before the 20 minutes timespan.

A couple of things come to mind here:
Is there any pattern to the lost authentications? Meaning, is it always after 20 minutes or is it really seemingly random?
Since you are on shared hosting, do you explictly set your machine keys in your web.config? If you do not and they are set to auto generate, the keys will be different if your application is load balanced. Thus you authenticate on server A and some subsequent request goes to server B, your application will not be able to decode the authorization cookie and 'kick you out'
In a Web farm, you cannot guarantee which server will handle
successive requests. If a user is authenticated on one server and the
next request goes to another server, the authentication ticket will
fail the validation and require the user to re-authenticate. The
validationKey and decryptionKey attributes in the machineKey element
are used for hashing and encryption of the forms authentication
ticket. The default value for these attributes is
AutoGenerate.IsolateApps. The keys are auto-generated for each
application, and they are different on each server. Therefore,
authentication tickets that are encrypted on one computer cannot be
decrypted and verified on another computer in a Web farm, or in
another application on the same Web server. To address this issue, the
validationKey and decryptionKey values must be identical on all
computers in the Web farm.
See here for more information on that second bit.

The session has a time out, if you go past it your session (and authentication) will get destroyed.
You could increase its timeout from web.config or, and this is the way I went, you could make a dummy page you ping with AJAX every few min. The advantage of the latter is that your session will still terminate in a timely enough manner when the user closes his browser, as opposed to staying there for half an hour using resources and preventing Application_OnExit from running.

Related

ASP.Net Forms Authentication - Login times out after 5-10 minutes

I've got an app in MVC5 which uses forms authentication. Since rolling it out to a server, after being logged in for 5-10 minutes you are logged out; I would like the login to remain for minimum 1 day.
I suspect this is because the app pool is recycled after 5 minutes of inactivity; unfortunately this is a feature of our hosting and I have no control over it.
I've tried a number of things to work around this:
Set persistent to true on the login call, i.e. forcing it to
"Remember Me".
Set the session state to use a SQL Server database,
with a timeout of 1440.
Set timeout under to 1440 in the web.config.
Forced all three computers that use the site to trust the site in the browser, to make sure the cookie isn't being destroyed.
Set Session.Timeout to 1440 in global.asax.cs (probably redundant when this is also set in web.config)
A few points of background:
The site uses autofac to instantiate the database connection, which interacts with OWIN.
Pretty much everything else regarding the login comes from a standard visual studio setup, meaning I created a new web project and set authentication to forms.
The cookie is still there after being sent to the login screen.
The session is still there (in the database) after being sent to the login screen.
Does anyone know how I might fix this issue?
Asp.net forms authentication cookie not honoring timeout with IIS7
For anyone wondering, the fix here appears to have done the trick. Specifically, setting the machineKey in the web.config.

shared authentication with cookie and token in identity server

I’ve an MVC application that uses identity server with cookie based authentication.
We created a new spa application that uses identity server authentication through bearer tokens.
Everything works fine, but the user is currently required to log in twice, once in each app.
Is there a solution to share the authentication session? I would prefer to not have to decrypt the cookie from the spa if possible.
Edit:
What I see is that the authentication code flow on the SPA is populating a lot of values on the session storage, which are not picked up by the the MVC (client credentials flow) application.
Am I supposed to reflect those changes manually? I see that both populate a cookie with the security information, but the SPA is just ignoring it.
In the end the reason was due to the difference in casing for the Authentication/authentication endpoint.
The cookies for idsrv and idsrvsession were marked as case sensitive, so we ended up having two different cookies for the session (hence creating 2 different sessions).
Changing one of the two endpoint to match the other solved the issue, although a CR forcing a tolowercase of the parameter has been requested to the library performing the connection to identity server.

Session-State In-Process (InProc) mode: When is it forgotten?

I'm using the InProc session-state mode in my web application.
In order to test the client's behavior on a session loss I restarted the web server, first just iis, then the entire machine. Both actions did not lead to a session loss.
This puzzles me: The session is stored on memory, right? How can the session be retained after the machine restarted? Does IIS dump the sessions on disk on a restart? If so, where is this documented and how do I flush the sessions for testing purposes?
I'm using IIS 8 on Windows Server 2012.
EDIT: I don't know whether I actually lose the session - what I know is that my cookie is still accepted. (I don't actually use any "session", I just need to authenticate the user.) It could be that the authentication ticket is usable even after the actual session is lost, as is suggested here.
EDIT: Also look here for more information about the forms authentication cookie and what's in it.
Contrary to what I assumed, the authentication entry in the cookie isn't merely an opaque identifier of a session, but actually a encrypted username with an expiry time. It is not directly related to a session at all, and its validity is independent of the validity of any sessions.
That means that the expiry of authentication and the loss of the session are two distinct events that usually occur at different times.
Look at this and this link for more information.

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.

What should I do If I want to maintain session between HTTP and HTTPS - Asp.Net

What should I do If I want to maintain session between HTTP and HTTPS.. In my site's public area some pages are HTTP and some are HTTPS but I want to keep common session for both..
Once your user's have authenticated they will continue to have the same session cookie until it expires whether they are accessing pages with HTTP or HTTPS. Make sure that you are using encryption on your session cookie to make it more difficult to crack if you are passing it over an insecure protocol. You might want to look at the wikipedia article on session hijacking for more information.
There are a number of session state modes in ASP.NET you can use (which can be configured in web.config) apart from the default "In Proc":
StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
Custom mode, which enables you to specify a custom storage provider.
See ASP.NET Session-State Modes on MSDN. I haven't tested this for HTTPS, but hopefully StateServer or SQLServer should facilitate this.
One session is maintained per application per user. So if you have one application which has some pages served over https and some over http, you do not have to worry about a new session being created when moving from https to http and vice-versa.

Resources