8

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

5 Answers 5

5

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();
}
3
  • Could you explain your first two points a little more please? What do you mean "if that data is in the forms membership provider / AD". They are a user and I can query AD by user name. "Otherwise you will have to query AD to get their name. " -I can do this if I have their name, but how would I do it to get their name?
    – Echilon
    May 14, 2012 at 15:15
  • The problem I have is that Thread.CurrentPrincipal.Identity.Name is empty, do I can't get the username.
    – Echilon
    May 15, 2012 at 7:48
  • Try turning off Anonymous Authentication, this lets people onto the site without authenticating, this is why they don't have any identity when you look for it.
    – Alex Moore
    May 15, 2012 at 12:27
1

The .Net apps I've written where I've used windows authentication I can still use User.Identity.Name to get the AD username. This usually includes the DC of course, and returns the users SAM Account name. I was not trying to implement both at the same time but User.Identity.Name for sure works separately

1

Try this if you are using forms authentication with active directory:

Context.User.Identity.Name

//code snippet

sub Page_Load(sender as object, e as EventArgs)
  lblName.Text = "Hello " + Context.User.Identity.Name & "."
  lblAuthType.Text = "You were authenticated using " &   Context.User.Identity.AuthenticationType & "."
end sub

Ref:
Active Directory Authentication from ASP .NET
How to authenticate against the Active Directory by using forms authentication and Visual Basic .NET Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

Ref: You can use Windows authentication with ASP.NET in a number of ways:

  • Windows authentication without impersonation. This is the default setting. ASP.NET performs operations and accesses resources by using your application's process identity, which by default is the Network Service account on Windows Server 2003.

  • Windows authentication with impersonation. With this approach, you impersonate the authenticated user and use that identity to perform operations and access resources.

  • Windows authentication with fixed-identity impersonation. With this approach, you impersonate a fixed Windows account to access resources using a specific identity. On Windows Server 2003, you should avoid this impersonation approach; instead, use a custom application pool with a custom service identity.

As per the documentation you can obtain the authenticated user's Windows token.

IIdentity WinId= HttpContext.Current.User.Identity;
WindowsIdentity wi = (WindowsIdentity)WinId;

If there is something wrong then check your application impersonation method as per the MSDN documentation of How To: Use Windows Authentication in ASP.NET 2.0

Refer ScottGu's article Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

1
  • NB: does not apply when Forms Authentication in use. I've used this with ASP.NET MVC, and System.Web.HttpContext.Current.User will be a System.Web.Security.FormsIdentity object. Jan 13, 2014 at 9:55
0

This is a segment of code I used in my ASP.NET MVC App not too long ago, it helped for me, Don't know if it will help you though, you are free to check though

    private static void CheckIfUserExists(string p)
    {
        try
        {
                var user = (from x in Data.EntityDB.UserInfoes where x.SAMAccountName == p select x).FirstOrDefault();
                DirectoryEntry entry = new DirectoryEntry(Properties.Settings.Default.LDAPPath); //this is the connection to your active directory
                DirectorySearcher search = new DirectorySearcher(entry);
                search.PropertiesToLoad.Add("*");
                search.Filter = "(&(sAMAccountName=" + p + ")(objectCategory=person))";
                SearchResult searchResult = search.FindOne();
            //If the user under the alias is not found, Add a new user. Else, update his current data
            if (user == null)
            {
                XXXXXXX.Models.UserInfo newUserEntry = new Models.UserInfo
                {
                    SAMAccountName = p,
                    First_Name = searchResult.Properties.Contains("givenName") ? searchResult.Properties["givenName"][0].ToString() : string.Empty,
                    Last_Name = searchResult.Properties.Contains("sn") ? searchResult.Properties["sn"][0].ToString() : string.Empty,
                    Title = searchResult.Properties.Contains("title") ? searchResult.Properties["title"][0].ToString() : string.Empty,
                    Office = searchResult.Properties.Contains("l") ? searchResult.Properties["l"][0].ToString() : string.Empty,
                    Country = searchResult.Properties.Contains("c") ? searchResult.Properties["c"][0].ToString() : string.Empty,
                    Telephone = searchResult.Properties.Contains("telephoneNumber") ? searchResult.Properties["telephoneNumber"][0].ToString() : string.Empty,
                    Mobile_Phone = searchResult.Properties.Contains("mobile") ? searchResult.Properties["mobile"][0].ToString() : string.Empty,
                    Email_Address = searchResult.Properties.Contains("mail") ? searchResult.Properties["mail"][0].ToString() : string.Empty,
                    Image_Path = string.Format(Properties.Settings.Default.UserPicturePath, p),
                    LastUpdate = DateTime.Now,
                };

update

Take notice that I also queried a different database in this extract, ignore all the Linq statements. The DirectoryEntry, DirectorySearcher and SearchResult Classes should help you with what you need.

update 2 the variable p can be replaced by the HttpContext.Current.User.Identity Property

update 3 Here is a current list of LDAP names (where you see searchResult.Properties.Contains("") Over here which points to different user attributes in the active directory

5
  • The problem is that HttpContext.Current.User.Identity is blank, and IsAuthenticated is false, so I have no username, even though I'm on an AD account.
    – Echilon
    May 14, 2012 at 14:39
  • Thats odd. have you set the <providers> tag in your web.config to your LDAP connection? because, if yes , and you can log in, HttpContext.Current.User.Identity should not be null
    – Eon
    May 14, 2012 at 14:54
  • <membership defaultProvider="ADMembershipProvider"> <providers> <clear /> <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" connectionUsername="SOMETHING" connectionPassword="SOMETHING" attributeMapUsername="sAMAccountName" enableSearchMethods="true" attributeMapEmail="mail" /> </providers> </membership>
    – Eon
    May 14, 2012 at 14:55
  • Sorry if its unreadable,was meant to be a quick reply, didnt think I copy pasted all :? check your webconfig if it is mapped at least
    – Eon
    May 14, 2012 at 14:56
  • I've added a web.config snippet.
    – Echilon
    May 14, 2012 at 15:19
-1

I'd give a try with:

var i = Environment.CurrentUser;

and you can use also my class: http://pastebin.com/xnYfVsLX

1
  • I don't think that will work for web apps, which I'm assuming this is since he mentioned forms auth
    – Eonasdan
    May 14, 2012 at 13:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.