ASP.Net (IIS 7.5) Querying Active Directory without User Credentials - asp.net

I have multiple web applications that I've built for our intranet. I wanted to allow users to not worry about logging in, so these apps pull the currently logged on user when they hit the site. I used this code for this to happen:
Dim userName As String = User.Identity.Name
CurrentUser = userName.Substring(userName.IndexOf("\") + 1)
This works like a charm, no issues here. The next step is to query Active Directory for that logged in user to pull various information. How I currently have it coded, it works like a charm on the devleopment side (typical because I'm not running IIS).
The problem becomes when I publish it to my IIS server (Windows Server 2008 R2 running IIS 7.5), I get error messages that point to the specific line in my code that queries Active Directory. The interesting part is these apps were working great last week. They broke after my server admin did the latest batch of Windows Updates (please note, I am running them using .Net Framework 4.0)
Before I had each app setup so that Windows Authentication was Enabled, the other Authentication types were disabled. For providers, Negotiate is #1, NTLM is #2. For Advanced Settings, Extended Protection = Off, and Enable Kernel-mode authentication is checked.
My web.config has the following set:
<customErrors mode="Off"/>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
These were the settings I had, and everything worked like a charm. Now to get it to somewhat work I need to swap the providers around so NTLM is #1 and Negotiate is #2. Because of this, the user's credentials are not properly passed in and the AD query fails. This is the coding I'm using for the query:
Dim adSearchRoot As New DirectoryEntry("LDAP://DC=[DOMAIN],DC=com")
Dim adSearch As New DirectorySearcher(adSearchRoot)
adSearch.Filter = "(&(ObjectClass=User)(sAMAccountName=" & CurrentUser & "))"
Dim searchResult As SearchResult = adSearch.FindOne()
Ever since the updates, when loading the site with Negotiate in front, it fails on that bottom line because I don't have a username/password set for the DirectoryEntry. Even when I set a username/password, it still does not 100% work like it used to.
So my question becomes, what do I need to do so that the user accesses the site, I can know their username, and can query active directory without requiring the use of a username/password in the DirectoryEntry??
Is it a setting in IIS?
Or do I need to recode?
web.config setting perhaps?
Do I need to revert server updates and figure out which one causes the break to occur?
Thanks for the advice in advance. If you have any questions to help answer the question, let me know.
UPDATE
I tried as Matt suggested by adding the following clip to my web.config file:
<security>
<authorization>
<add accessType="Deny" users="?" />
</authorization>
</security>
This did not work. I did some reading, and then altered this section further:
<location path="Default Web Site/NameOfApp">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false"/>
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>
<authorization>
<add accessType="Deny" users="?" />
</authorization>
</security>
</system.webServer>
</location>
In doing this I also removed the string that was higher up in my web.config section. This did not work either (fyi, this was a great reference http://www.iis.net/ConfigReference/system.webServer/security/authentication)
I then tripped across this article: http://social.technet.microsoft.com/Forums/en/winserverDS/thread/7deba16b-295a-4887-98f9-9f291ed49871 which seemed to be a similar situation. This article eventually referenced "Double Hops", after looking into this and trying a few things, this didn't solve my issue either.
Next Step
I am going to try a new IIS 7.5 implementation on a different Server 2008 R2 system and essentially start from scratch, to see if the problem recreates or not.
ANY new suggestions would be of great help.

I was able to make the code execute without any problems on a Windows 2008 Server. I created a new .NET 4.0 application pool and assigned it to the web application. I changed the web.config to deny anonymous access and use Windows authentication. The code executed without exception.
Looking at your web.config clip, I wonder if this might be what you're missing:
<system.webServer>
<security>
<authorization>
<add accessType="Deny" users="?" />
</authorization>
</security>
</system.webServer>
It's important that you have this authorization section within the system.webServer section. IIS 7 uses the system.webServer section to store some settings that were part of the metabase in IIS 6.

I had this same problem. Here's how I solved it:
Use overload 4 of 5 for the DirectoryEntry constructor which allows for not only a path, but a username, and a password as well. So, your AD connection should look like this:
DirectoryEntry adSearchRoot = new DirectoryEntry("LDAP://DC=[DOMAIN],DC=com", "DOMAIN\Username", "Password");
DirectorySearcher adSearch = new DirectorySearcher(entry);
Now, instead of "DOMAIN\Username", use a service account and then for the password, obviously, use the password for the service account.
I think as long as the service account is a member of the "Domain Users" group, then you should be able to query AD no problem.

Related

Issues with some users in Win Authentication in ASP.NET

I would like to get some help in my strange issues,
I have an ASP.Net 2.0 application with VB.NET Code behind,
I set up my application to enable only Win authentication
So in IIS all disabled except Windows auth,
In My Web.Config i have the following under system.web:
The Web.Config contains the following :
authentication mode="Windows"
authorization>
deny users="?"/>
/authorization>
identity impersonate="false"/>
Now some users when they enter to my ASP application they get prompted for user name and password , then they logged in successfully,
some users the application fails on Page.User.Identity.Name
and return Object Reference Error,
Im using VS2010 and ASP.NET 2.0 frameword 2.0 and IIS 7 under Win 2k8 R2 latest SP's installed.
All users are Domain users.
Thank you,
Can you access the username by HttpContext.Current.User.Identity.Name? You can also check if authentication was successful, and what method of auth was used.
Windows authentication uses kerberos by default in iis I believe, which may not work for a lot of reasons (I think there are problems in Firefox for example ), when this fails, it is falling back to ntlm. Try removing the negotiate authentication provider and use just ntlm. If this works, you will have the fun of diagnosing kerberos problems :-)
Trogvara,
Thank you for your posting ,
I'm new to the site and tried to formatted but it did what we see now,
the Web config setting is :
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
<authorization/>
<identity impersonate="false"/>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
Hope that clears the setting in Web.config
Thank you,

HttpContext.Current.User.Identity.Name returns blank

I am using HttpContext.Current.User.Identity.Name to get the user name when the web application is in use. During development I was using my local iis, with integrated windows authentication enabled and anonymous access enabled and disabled, and I was able to get the username.
Now, when I publish the web application, it comes back blank. The setup on the published server is the same, and I have tried using Page.User.Identity.Name, which also returned blank.
Does anyone know why this is and how to fix it?
You probably had Anonymous Authentication on as well as Windows Authentication. Turn off Anonymous off.
So,
<system.web>
<authentication mode="Windows" />
</system.web>
In IIS config for the app,
look in Authentication tab
Set **Anonymous Authentication** to **Disabled** and
Set **Windows Authentication** to **Enabled**
This should work and the Identity.UserName should now show up properly.
HttpContext.Current.Request.LogonUserIdentity.Name always work for me in VS 2012 environment and IIS 7
To solve the problem, you have to enable the Windows Authentication feature. Follow the below steps:
-Click Start, and then click Control Panel. Open the Programs group.
-Under Programs and -Features, click Turn Windows Features on or off.
-Expand the item labeled Internet Information Services.
-Expand the item labeled World Wide Web Services.
-Expand the item Security ->
Make sure to select Windows Authentication
Also you need to disable Anonymous Authentication from the IIS as follows:
-Click on your application in IIS
-Double click Authentication under IIS group
-Click on Anonymous Authentication
-Click on Disable on the right side under Actions.
Hope this helps
When working with WIF you should use Thread.CurrentPrincipal.Identity.Name instead of User.Identity.Name.
Read more here: http://msdn.microsoft.com/en-us/magazine/ff872350.aspx to learn more about Windows Identity Foundation
Similar question: User.Identity.Name is null after authenticate via WIF
set <authentication mode="Forms"> in web.config file & Your Problem Will solve.
Test your web-site by using below code
if (Page.User.Identity.Name != "" )
{
Label1.Text = "Hello";
}
else
{
Response.Redirect("login.aspx?url=Upload.aspx");
}
This will not solve the original post, but want to put this here anyways in case others stumble across this when searching for why user.identity is returning nothing...
In my case User.Identity started returning nothing after updating a users ad username (specifically the pre-windows 2000 username).
The LSA cache on IIS was the issue. Even after restarting the IIS server while troubleshooting the issue persisted. It was not until adding the registry setting outlined here the the issue was fixed:
https://support.microsoft.com/en-us/help/946358/the-lsalookupsids-function-may-return-the-old-user-name-instead-of-the
For a blank return, my solution ended up being the web.config. I'm using Visual Studio 2010, and the default web.config did not work. I replaced it with a nearly empty web.config and then success! Perhaps the default vs2010 web.config called too many references or configured the IIS incorrectly for the use of User.Identity.Name. My system is Windows7.
Default asp.net web site web.config from vs2010 was about 100-115 lines long. As you can see below the nearly empty web.config is about 20 lines long.
the web.config that i used:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<allow roles="Doman Name\Group Name" users="" />
<deny users="*" />
</authorization>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<security>
<authorization>
<add accessType="Allow" users="" roles="Doman Name\Group Name" />
</authorization>
</security>
</system.webServer>
</configuration>
In IIS: click on your Site.
In Home Page: Authentication.
In Action menu: Open Feature.
Disable Anonymous Authentication.
Restart Site.
steps 1,2,3
step 4

User.Identity.Name sometimes blank with Windows authentication

My web app uses Windows authentication. All other authentication methods are disabled.
It works at first; User.Identity.Name returns "MYDOMAIN\myuser." However, if I wait 131 seconds (yes, I timed it, though I'm not sure it always takes exactly that long) and reload the page, User.Identity.IsAuthenticated = false and User.Identity.Name = "". At this point I can just reload the page and it works again, for another 131 seconds of inactivity.
Relevant parts of web.config:
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<identity impersonate="false" />
...
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
More information, possibly relevant:
My solution is deployed to two different IIS applications. The first one is for internal users; it just uses Windows authentication. The second one is for external users; it uses anonymous authentication (in the root folder only) and forms authentication. I'm only having problems with the internal site.
The web.config file under the Account folder was allowing anonymous authentication (the one I posted with my question is the main web.config). Not sure how that happened, but removing it fixed the problem.

User name in asp.net

I tryed this ways:
Request.ServerVariables["LOGON_USER"]
or
HttpContext.Current.User.Identity.Name
or
User.Identity.Name
-- If i run it by F5 from VS2010, it runs OK.
-- If i run it on IIS (I tryed it on 5.1 and 6.0, other IIS i can't use) there are empty strings.
In web.config i have:
<authentication mode="Windows"/>
<authorization>
<allow users="*"/>
</authorization>
so, all users should by autentificated.
Maybe, there should be more things in web.config.
I tryed it in IE, Firefox, and Chrome.
I post this question before, but there was some misleading information, so i post it again.
so, all users should by autentificated.
Exactly. All users include anonimous.
Any web browser will attempt an anonymous request at first, if it's successful it won't try to authenticate. So you want to deny anonymous requests:
<authentication mode="Windows" />
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Note that the order of items in the authorization element is important - they're like any access rules in that they're processed from top to bottom.
In this case the ? is anonymous users and * is all users (including anonymous) but as the deny anonymous user statement comes first - they will be denied and never get to see the allow statement which allows everyone else.
Also, if this is an ASP.NET MVC 3 web application, there're some quirks to be heedy of - please correct me if I'm wrong as I don't recall all the details right now:
<appSettings>
<add key="autoFormsAuthentication" value="false" />
</appSettings>
The autoFormsAuthentication has to be disabled to enable Windows authentication in an MVC 3 web application - or it was anyway, it might have been fixed by now but as it took quite some time to figure it out, I'm including it here. The symptom when not disabling it is every authentication request is redirected to the account forms url (which you might not even have).

IIS7 Mixed Mode Authentication

We're getting ready to start migrating some of our IIS6 sites to IIS7, and the application currently uses Forms Authentication. We have started getting some requests from various sites to use the Windows Authentication for the users. While this is easy enough to implement (and I've shown internally that there is no issue with the app, as expected) the question then is how to continue to keep Forms authentication for when Integrated Windows doesn't work. I've seen several walkthroughs on how to have it configured on IIS6, and I could do the same thing on IIS7, but then I have to turn on Classic Mode processing. Any solution should also be back portable to IIS6, if possible, to keep the build tree simple.
So what are my options on this? Do I setup the app with Integrated Windows Authentication in IIS7, Forms Auth in the web.config, and redirect 401 errors to an "error page" allowing them to login using forms, then back to the regular app?
The case when Forms is likely to be needed is going to be reserved for Contract workers, our support staff, and if someone needs to access it on their site from their Extranet. So primarily it's for our staff to login to check functionality and confirm bug reports. I suggested we just maintain that for our support staff to work, we need a Windows login that will always be live, and then we'll just enforce local responsibility on who can login to the site, but I'm told that we would do better to have Forms Authentication.
Any thoughts? I can post some of the links of the articles I've already read through if that would help the forum better narrow my needs.
tl;dr: How to do mixed mode authentication (forms, windows) in IIS7 without changing to classic pipeline and still be able to use the build in IIS6 if possible.
No, that's not quite right, but I can't do a code block in a comment reply, so I'll post a new answer ...
The following code block allows me to control anon access from IIS7 without having to muck about in the metabase (where GUI changes on IIS6 get applied)
<location path="WindowsLogin.aspx" >
<system.web>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
thanks for getting back to me, I have been playing round with several of the implementations on and off for a few weeks now, that I've read about on the internet (javascript, 401, 2 virtual directories) but still havnt really found anything that works as I wanted. We will be potentially rolling it out to more than one client-each with different hardware/setups even different versions of iis, so wanted it to be as generic as possible. Ive come up against a brick wall on a couple of the suggested solutions...
when you say for IIS7+ you removed anon access in web config, I assume like this: -
<location path="Authent/WinLogin.aspx" >
<system.webServer>
<security>
<authorization>
<add accessType="Deny" users="?" />
</authorization>
</security>
</system.webServer>
</location>
I spent a few days trying to get this to work, with a slight difference... I wanted the first login screen to present the forms login with an button underneath "Login With Windows Authentication".
I eventually gave up on all these techniques, as I never could quite get the satisfactory results. My workaround was as follows, and works perfectly:
Create a separate website "LoginWithIntegratedSecurity"
Set this up with integrated security
This web site creates a temporary "User Hash Key" in the database, which identifies the user
Redirects back to LogonPage in Forms Authentication website with Hash key in url
LogonPage in Forms Authentication checks for Hash key, and logs user in after database check
So if the User clicks the button "Login with windows Authentication", the server redirects to the windows authentication site (passing the "ReturnUrl"). This site challenges and logs in user, then redirects back, again passing the "ReturnUrl" as well as the HashKey.
This all happens very fast, and appears pretty seamless.
I know its a hacky workaround, but for my case it worked well.

Resources