Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveDirectory Current Username in ASP.NET

I'm trying to get both ActiveDirectory and standard forms login working but one thing is stopping me. I can't get the name of the current windows user. The closest I've got is var i = WindowsIdentity.GetCurrent();, but that gives me the name of the IIS app pool user. I have Anonymous Authentication, Forms Authentication and Windows Authentication enabled in IIS. I can load users from AD so I assume my web.config is setup correctly.

Edit: This is my web.config (using a Facade provider):

<membership defaultProvider="HybridMembershipProvider">
      <providers>
        <clear />
        <add name="HybridMembershipProvider" type="MyApp.Data.HybridMembershipProvider" AspNetProviderName="AspNetSqlMembershipProvider" ActiveDirectoryProviderName="ADMembershipProvider" />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyAppConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
        <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" 
            attributeMapUsername="sAMAccountName" enableSearchMethods="true" attributeMapEmail="mail"/>
      </providers>
    </membership>

Edit 2: Here's my IIS security setup.

IIS Security setup

like image 743
Echilon Avatar asked May 14 '12 13:05

Echilon


People also ask

How to get Current UserName in c#?

GetCurrent(). Name; Returns: NetworkName\Username.

How to get Current user name in ASP.NET core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);


1 Answers

If you turn on ASP.Net Impersonation in IIS, you can get the username like you wanted to. This will only work if that data is in the forms membership provider / AD, and they are not Anonymous.

Also, mixing Forms based and Windows/AD based auth is doable but not recommended. See this if you need to do it.

EDIT: I think I misunderstood what you wanted so here's a high-level glossing over of what goes on with the aforementioned solution:

If you turn off Anonymous Authentication, and turn on Asp.Net Impersonation, IIS will do a 401 Challenge whenever somebody visits the site.
If everything is on the same domain, the web browser will send your credentials to IIS, IIS will validate them against it's Active Directory, and then AD will give IIS an Identity to work with.

When you have Asp.Net Impersonation turned on, IIS will then bind that Identity to the current thread/request. So after authentication happens, you can just grab the username from the current thread identity, and then query Active Directory like:

using System.Threading;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

......

PrincipalContext pc = null;
UserPrincipal principal = null;

try
{
    var username = Thread.CurrentPrincipal.Identity.Name;
    pc = new PrincipalContext(ContextType.Domain, "active.directory.domain.com");
    principal = UserPrincipal.FindByIdentity(pc, username);

    var firstName = principal.GivenName ?? string.Empty
    var lastName = principal.Surname ?? string.Empty
    return string.Format("Hello {0} {1}!", firstName, lastName);
}
catch ...
finally
{
    if (principal != null) principal.Dispose();
    if (pc != null) pc.Dispose();
}
like image 115
Alex Moore Avatar answered Sep 23 '22 12:09

Alex Moore