Logs out and with every refresh though not using TempDataProvider? - asp.net-mvc

I've got an app built using asp.net mvc and deployed over 2 Amazon EC2 instances. I'm using forms authentication to authenticate users. I simply make a quick look up on the given username and password and if I found a match I set an authentication cookie, like so:
if(_repository.Login(username, password))
FormsAuthentication.SetAuthCookie(username, false);
This works fine as long as the application on one machine, but, once I leveraged Amazon Elastic Load Balancing to deploy the site on two machines, the site behaves in a very weird way. When a user logs in, the site recognizes a logged in user, after a refresh or two, the site no longer see the user as a logged in user. If the user keeps refreshing again for some time, the app sees the user as a logged in user again, and this goes forever.
I'm aware that such a problem might occur if I'm storing SessionState inproc. I'm not using SessionState at all.
What am I missing here guys?
Ps: I've edited the session state to be stored on a state server [Though i'm not using neither sessions nor TempData anywhere on my app] and the same weird behavior is there.

You need to synchronize your <machinekey> between all servers in your farm. Otherwise the forms authentication ticket is only good for the machine which issued it. I doubt this has anything to do with Session/TempData.

Related

Centralised Login to multiple rails servers

The situation:
We have a rails application, which runs on 12 different servers (different sets of customers). User credentials are stored in the database of each server. We use Devise for auth.
We have an Android app that, when logging in, you have to select the correct server to connect to.
Requirements:
A centralised login page so users don't need to know which server/url to log in to. This is for the web and android. The user should either:
a) Type their username/email, and be forwarded to the correct server to login.
b) Type their username/email AND password, and be forwarded and logged in to the correct server.
Current Ideas:
Create a NoSQL db table with a list of usernames/emails with the server they need to log in to, the login page can grab the server and forward you on.
Use something like Auth0 to manage user data - however unsure how this would work with our current User credential tables spread across multiple servers.
This is not something I have a huge amount of knowledge on, and looking for criticism of the above ideas/better approaches.

401.0 - Unauthorized - MVC App with IIS 7

I've got an MVC app that normally works fine, but on a particular server, it's returning a 401.0 "The authenticated user does not have access to a resource needed to process the request" error.
Normally it works like this:
User logs into a separate application, gets a user ID and token, clicks a link into this application. User ID and token go into the URL.
User gets into my application with Anonymous auth, and then in our LogonAuthorize filter, we get the ID and token from the query string to authenticate the user.
I have logging in the filter, and I can see the user getting authenticated. So, they're making it at least that far. However, instead of the page they're supposed to see, there's a 401.0 Unauthorized error from IIS.
Things I have tried:
Giving IUSR access to the directory
Running mirate.exe (it's an Entity Framework app)
Removing all [Authorize] attributes in the solution... I know that we make it as far as the Initialize() event of my BaseController object. We don't seem to make it into the specific controller actions, such as Home/Index, which inherits BaseController. I don't see any logging after BaseController.Initialize().
Giving Network Service access to the directory
Switching the App Pool from Integrated to Classic (I get a blank screen instead of a 401.0 error, which is odd. Same authentication stuff in the logs.)
Using a local user account instead of Network Service with the app pool, giving that account access to the directory
Setting different accounts to be used by "Anonymous"
Rebuilding and redeploying the app (several times)
Different authentication schemes: Turning on Windows auth gives a 401.1, turning off all of them gives a 401.2
Making sure Global.asax is in the right place
aspnet_regiis -i
Tearing all my hair out (counterproductive)
I set up a tracing rule for this error, and I have a trace, but I have no idea how to read it. I would paste it here, but it's a pretty long XML file.
The error comes from module ManagedPipelineHandler, notification ExecuteRequestHandler, handler System.Web.Mvc.MvcHandler, with error code 0x00000000.
One detail: This server is configured to use port 90 instead of port 80. I'm not sure why that would cause problems, but maybe it would?
One other detail: The app in question is running as an application in a virtual directory underneath the "main" application, which is configured as the root website.
One new detail: This server is Windows Server 2008 R2, and was upgraded from Windows Server 2003. I believe something in the upgrade process may account for the issue, as none of the "usual suspect" solutions to this type of problem have helped.
So you have found the solution but seeking clarification why it worked. This can be one of the scenario.
Seems your website/web application was hosted through specific user credentials that was expired. Next time when you remove & add windows authentication through new credentials or application pass through it worked.
I face similar situation in one of our test web application that is hosted using specific user Path Credentials. Each time user password is changed/expired. Web application stops working.
Windows authenticates first with Kerberos. Next it attempts other authentication methods. Your requirement was NTLM. Turning off all but Windows Authentication forced the application to attempt NTLM which succeeded.
It seems that the solution here was to turn on Windows auth and turn off every other form of authentication, which is counterintuitive. But there you go... that's what made it work.
If someone wants to post an answer explaining WHY that was the answer for me, I'll award them the bounty.

Rails, Devise, and multiple domains

Let's say I have an application that's going to be accessed from completely different domains that all point at the same server*:
example.com, example.net, foobar.com, ...
I have a Devise based authentication system that's worked fine before. However, the goal is now to add HTTPS to the sign in system. The problem is, as it turns out, there is no way to host more than one HTTPS website on the same IP address**. To resolve this problem, I set up the login pages to always POST to https://secure.example.com. As far as I can tell, this is working fine. Devise seems to have no qualm with it. However, the tricky part is that the user now needs to be redirected to foobar.com, which also needs to understand that the user is logged in. I pass the site to return to in a hidden parameter in the login form, and the redirection works fine. I still have no way to inform foobar.com that the user is now logged in.
I've managed to set it up so that, upon being returned to foobar.com, it copies the user's session cookie for secure.example.com into a new cookie for foobar.com. This part is working fine. However, in the Rails console, the web requests for secure.example.com and foobar.com - with the same cookie sent for each - produce two completely different sessions and therefore, it's no wonder Devise acts like the user was never logged in to foobar.com
Does anyone know why this wouldn't work - why two identical web requests (only the domain of the request URI was different - I tried it in Firebug, too) would produce two completely different sessions in a Rails 3 app with different, yet consistent, session ids? More to the point, does anyone know how to MAKE this work?
* assume, for the purposes of this exercise, that this is unavoidable and the sites cannot be hosted all under different subdomains, and that the number of domains required is too great to get a separate IP address for each.
** unless they're subdomains and you have an *.example.com cert, but that's beside the point.
If you're already using Devise, I suggest you try using token authenticatable. You can generate a token for the user in question, redirect them with the token to sign in, and then quickly expire the token after they have signed in.
You could also try rolling your own OAuth provider with doorkeeper.

ActiveDirectoryMembershipProvider and Forms authentication

I've got a ASP.NET MVC web app which uses forms authentication.
I'm using ActiveDirectoryMembershipProvider to validate users against our domain.
if (Membership.ValidateUser(m.Username, m.Password))
{
FormsAuthentication.SetAuthCookie(m.Username, true);
....
This means the user gets validated only when they log in.
Problem with that is ofcourse that if the user's password changes they still remain logged in. Or worse, user leaves our company with a grudge, and they still have access.
I would have thought such a simple use case would have an obvious answer but I've been stuck on this for a while now.
I could put the users password in the session and then validate it every time, but that doesn't feel right.
What is the suggested/correct way of handling this?
The typical solution is to force log out when users unsubscribes from the service or less commonly when they change password. Use this method:
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
If the user can be deactivated outside of the app (i.e. Active Directory), the typical practice is to rely on the session time-out and perhaps ask for the credentials once more for critical operations. If you absolutely cannot allow the deactivated user to work while the session is still active, then yes, you'll have to check the credentials on every request. Since storing the password in the app is a very bad idea, it means you'll have to ask for credentials on each request which arguably is an even worse idea.
As for the password change, it normally doesn't modify the user's permissions so it should be harmless to allow for them to continue working.
The answer is to periodically (every 30 minutes or so) check User.IsApproved and User.LastPasswordChangedDate to make sure the users credentials are still valid.
To do this you need to manually create the FormsAuthenticationTicket and cookie, rather than using FormsAuthentication.SetAuthCookie.
Put the date you validated the user inside UserData and compare this against LastPasswordChangedDate.
I've implemented this and it works perfectly.
More information here
Check if Active Directory password is different from cookie

ASP.NET MVC FormsAuthentication.SignOut doesn't work

I'm trying to use forms.signout but sometimes it does not log out the user and he still can navegates through the website.
How can I resolve this? I also configured web.config forms authentication, but it's still not working.
I'm using FormsAuthentication to autenticate an user passing he's login.
Thanks!!
I don't know what the cause is but a few things you might consider/try
are they actually able to still visit pages generated by the server or are they just going back to locally cached versions? What happens when they cause a postback that has code to check if they are authenticated does that work or does it fail? I think the later meaning they are signed out but viewing cached versions of the logged in page in which case you want to instruct the client not to cache the pages using for instances:
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
You can try manually setting the cookie to be expired but this is a hack
FormsAuthentication.SignOut();
Context.Response.Cookies.Item(FormsAuthentication.FormsCookieName).Expires = Date.Now;
Response.Redirect("~/Somewhere.aspx");
Does the user have the domain (or a parent domain) in their trusted sites or intranet sites? I've run into some issues recently where a user is authenticated, but anonymous under circumstances where this is true. In my case it could also be that a parent site was, at one time, configured to allow windows integrated authentication. I've removed since removed that, but it didn't seem to help the problem. I haven't yet restarted IIS to see if this would have an effect. I've resorted to checking both that the user is authenticated and non-anonymous to ensure that the proper parts of the view are rendered. This is actually more accurate even though my login code should prevent having an anonymous login.

Resources