401.0 - Unauthorized - MVC App with IIS 7 - asp.net-mvc

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.

Related

How to fix problem with users Identity in Asp MVC .Net Application? Sometimes user is wrongly recognized as another one

I have a problem with Asp Net MVC4 web application. I am using Windows Authentication and IIS7. User is authenticated based on Active Directory and from time to time (like in 1-3% of all users attempts to the website) user is recognized as someone else who at the same time also entered the website (I checked it in IIS logs).
There is about 10 places in the code where I need to get user current name and I get this data using this:
HttpContext.Current.User.Identity.Name
I have already tried to cache username at the very beginning, when user enter the website and then use this cached username instead of accessing it via HttpContext. And surprisingly issue was occurring even more often.
I also tried to change settings in IIS like described here: https://serverfault.com/questions/360083/iis-7-windows-authentication-wrong-user
But issue still occurred.
Please let me know what else could I try? This issue really haunts me :)
Thank you in advance for the answer!

HttpContext.User.Identities has the same Identity twice

I have configured a .NET MVC application to authenticate against a separately running Identity Server (IdentityServer3). I have configured OpenIdConnectAuthenticationNotifications.SecurityTokenValidate() to place the user's claims into the AuthenticationTicket. Everything seems to be working as expected. The first time I access a page in the MVC app I get the Log In screen and after logging in I am redirected to the requested page.
But, when I look at the HttpContext.User (using a breakpoint in my override of CheckAccessAsync()) it has 2 identities. Looking closer I can see that both identities are the same, and that accessing the Claims property returns all of the claims twice.
Any ideas what I might be doing wrong?
I believe I have figured out what this issue is. I had configured the Authentication Server and the MVC app to use the same client, which actually caused other problems.
When I changed the Authentication Server to use its own client, the HttpContext.User in the MVC app still has 2 Identities but the Claims collection are not duplicated. I'm guessing that the Claims collection only contain the claims for the client that is accessing the collection. But I be totally sure since both clients return the same Claims collections.

Logs out and with every refresh though not using TempDataProvider?

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.

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.

Setting up a private beta for a website

I'm trying to setup a "private beta" for a site that I'm working on. The site uses open id. I don't want anyone to even browse the pages if they aren't part of the beta. What's the best way to implement this? Any suggestions?
For example:
When the site goes live, users will go to http://www.mydomain.com which will not require them to log in.
For the beta I want to restrict access. Users that go to http://www.mydomain.com will be redirected to a login page. Anyone attempting to access ANY PART OF THE SITE who is not authenticated will be redirected back to the login page.
I could stick [Authorize] attributes all over my controller actions, but that seems stupid.
If you're using ASP.NET MVC, it comes with authentication/authorization out of the box. You should be able to use that to setup authentication on your site.
Alternatively you could setup app server settings - IIS lets you setup username/password on a specific site it's serving, regardless of what the actual application may do. If you have access to the app server this might be the best solution.
If you're using IIS6, you can setup authorization easily. Right-click on your site > Properties > Directory Security Tab > Authentication and Access Control > Edit, and enter a username/pwd of your choice. Done.
The real question is how are they being invited to the private beta?
You could setup a password which drops a cookie much like serverfault.com does.
OR
If you know who you are inviting: you could add them to the system before hand using the email/login information that you already know about them (assuming you are inviting them via email)
I have implemented a function in a web application a while ago where we go the possibility to block access to the full website unless the user was an administrator (which in our case meant that the user account was a member of a specific group in Active Directory).
It was based on two things. First, all pages in the web application inherited not directly from the Page class, but from a custom page class in our web application. Second, we had a value like this in the appSettings section of web.config file:
<add key="adminaccessonly" value="0" />
The custom page class would check that value when loading. If it was not 0 it would redirect to a page (that did not inherit the same custom page class, though) informing the user that "the site is not available right now". If the value was 0 the page would load as usual.
In that application we used this to be able to take the site "offline" when we deployed a new version, giving us some time to verify that all was good before we let in the users again.
Best way are invitation system (based on invitation code) or manually confirmation access after create profile in your system. imho
Or you could host the site on a private server, and set up a VPN to use it. Depending on your resources and needs this may be the easiest and most secure way to do what you want without modifying your codebase.
OR alternatively you could use Apache or IIS to force authentication on access to the website directory. Keeping the authentication info in .htaccess for a while.
Even though you use open id authentication, you may still need some form of authorization mechanism. The simplest form would be a user-roles system in your database that assigns different roles to users
In your case, just assign the private_beta role to your private beta invitees and ensure you your authorization mechanism that all users have private_beta privilege before they may continue.
If you don't want to provide authorization for the public site (where everyone can do everything, once authenticated), then, you may only need to do a quick-and-dirty post-processing (for private beta only) on your open_id authenticated users to check them off a short list (which you can store on a text file.

Resources