HttpContext.Current.User.Identity.Name returns blank - asp.net

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

Related

Windows Authentication doesn't work with IIS Express 10

At work we were forced into a hardware refresh where we went from a Windows 7 box with VS 2013 and IIS Express 6 to a Windows 10 box with VS 2017 and IIS Express 10. The problem is that Windows Authentication refuses to work. I get a 401.2 - Unauthorized with the explanation of "Invalid Authentication Headers".
I've checked the web.config and the properties for the web project and they are correct. I've modified the applicationhost.config file in the .vs folder in the project to enable windows authentication. I even checked the permissions of the files to make sure authenticated users had the right permissions. None of this has worked.
This all worked fine in IIS Express 6. What did Microsoft change in IIS Express 10 that screws this all up?
Edit: have to manually type this stuff in, since I can't move code from the dev machine.
web.config:
<system.web>
<customErrors mode="off"/>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>
</system.web>
If you want any other sections of the web.config, ask me.
As for ApplicationHost.config, it is basically whatever VS2017 creates, since this is a fresh machine and there wasn't an existing one with the project. Changes I tried making:
<windowsAuthentication enabled="true">
<anonymousAuthentication enabled="false" userName="">
<section name="windowsAuthentication" overrideModeDefault="allow">
One additional datapoint: The application runs on Firefox. I can log on fine to our test servers, running IIS 8.5, but can't access the application on IIS Express.
I've since created a new MVC application and just ran that. It runs fine in IE, but it won't authenticate users from Firefox and Edge.
Edit: Found out that Edge doesn't support Windows Authentication on localhost: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4776775/
Still need to get it to work with Firefox.
Edit again: So, I think I know what is going on. I have two user accounts: the regular user account and an admin account with more privileges. What I did under Windows 7 was that while I logged into my regular account, I ran VS under my admin account. Then I could run my web application and log into the web site with my admin account. This doesn't seem to work anymore. The only way I could get my application to work is to run it all under my admin account. Otherwise, Windows authentication won't work. Security-wise, this is broken as hell and I'd like to find a better solution.
you only need to change some properties in your project as mentioned in below link!
enable windows authentication
I'm going to mark this one as answered and I'll follow up with a new question. The current solution is to run everything on our admin account to get windows authentication working. Not ideal.

HttpContext.Current.User.Identity.Name is null

I'm trying to use HttpContext.Current.User.Identity.Name to get the user's Windows login details from the internal network, however it's empty.
I've tried changing the authentication mode in Web.Config with no joy:
<system.web>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
I've also heard that in the project properties you should enable Windows authentication and disable anonymous authentication like so:
But then I get a re-direct loop, with the message "This webpage has a redirect loop" in Chrome.
I've also checked that Windows Authentication is installed on my machine:
Any ideas on how to fix this please?
Many thanks
When I have:
<authentication mode="Windows"/>
<identity impersonate="true/>
in web.config I get the current user with:
string currUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Changing my project web server settings to Local IIS instead of IIS Express resolved the issue for me, though I'm not sure why this is the case if anyone has additional information about this.
Right click the project
Click Properties
Go to the Web tab
In the Servers section, select Local IIS from the dropdown

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,

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

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.

ASP.NET Forms Authorization

I'm working on a website built with pure HTML and CSS, and I need a way to restrict access to pages located within particular directories within the site. The solution I came up with was, of course, ASP.NET Forms Authorization. I created the default Visual Studio log in form and set up the users, roles, and access restrictions with Visual Studio's wizard. The problem is, I can't log in to the website with the credentials that I have set.
I'm using IIS 7.
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I'd guess (since I don't have IIS7 handy ATM) that you'd need to turn off Anonomyous Auth, and enable Forms Auth in the IIS7 sections.
At what point did you insert your login/password? Did you have a look at the tables that where created? Althought your password must be encrypted, maybe it's worth just checking if your user was actually created.
At what point did you insert your login/password? Did you have a look at the tables that where created? Althought your password must be encrypted, maybe it's worth just checking if your user was actually created.
Forms Authentication does not require any form of user database.
Steve, can you please paste in your forms authentication web.config section, also any relevant code to the ASP.NET Login control you were using.
There is not enough information to troubleshoot here yet :)
The web.config section is pretty useless as far as I can tell:
<authentication mode="Forms" />
I looked in IIS 7, and in the Authentication section it says: Anonymous Authentication = Enabled, ASP.NET Impersonation = Disabled, Basic Authentication = Disabled, Forms Authentication = Disabled.
Also, I have made no changes to the code other than dragging a Login object onto the designer and changing the page it points at to index.html.
Currently, the log in fails by displaying the log in failed text.
EDIT: Earlier when I would try to navigate directly to a page that is restricted, I would receive a blue page saying that I had insufficient permissions. Now I can see the pages that are restricted without logging in even though I have anon access denied.
Steve,
I don't think the issue is with your IIS settings. Because forms authentication does not rely on IIS authentication, you should configure anonymous access for your application in IIS if you intend to use forms authentication in your ASP.NET application.
Try this in your web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Forms" >
<forms loginUrl="~/login.aspx" defaultUrl="~/">
<credentials passwordFormat="Clear">
<user name="YourUsername" password="superSecret" />
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<system.web>
</configuration>
There are better ways to implement forms authentication than hardcoding a username and password into your web.config, but this should work for getting you started.

Resources