Current ActiveDirectory Name in ASP.NET

I am trying to run both ActiveDirectory and standard forms, but one thing stops me. I cannot get the name of the current Windows user. The closest I have is var i = WindowsIdentity.GetCurrent(); but this gives me the IIS application pool username. I have anonymous authentication, form authentication, and Windows authentication in IIS. I can load users from AD, so I assume that my web.config is configured correctly.

Change This is my web.config (using the 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 is my IIS security setting.

IIS Security setup

+6
source share
5 answers

If you enable ASP.Net impersonation in IIS, you can get the username as you like. This will only work if this data is in the membership provider in forms / AD and they are not anonymous.

In addition, mixing auth-based forms and Windows / AD is performance-based, but not recommended. See this one if you need to do this.

EDIT . I think I misunderstood what you wanted, so here comes a deep understanding of what is happening with the above solution:

If you turn off anonymous authentication and enable impersonation of Asp.Net, IIS will call 401 when someone visits the site.
If everything is in the same domain, the web browser will send your credentials to IIS, IIS will check them against it in Active Directory, and then AD will provide IIS Identity to work.

When you enable Asp.Net impersonation, IIS will then bind this Identity to the current thread / request. Therefore, after authentication, you can simply take the username from the current stream identifier, and then query Active Directory as:

 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(); } 
+4
source

The .NET applications that I wrote where I used Windows authentication, I can still use User.Identity.Name to get the AD username. This usually includes a DC, and returns the SAM user account name. I did not try to implement both at the same time, but User.Identity.Name probably works separately

+1
source

Try this if you are using forms authentication with an 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 with Active Directory using forms authentication and Visual Basic.NET Creating secure ASP.NET applications: authentication, authorization, and secure communications

Ref: You can use Windows authentication with ASP.NET in several ways:

  • Windows Authentication without impersonation . This is the default value. ASP.NET performs operations and accesses resources using its application process identifier, which is the default network service account in Windows Server 2003.

  • Windows Authentication with impersonation . With this approach, you personify the authenticated user and use it to perform operations and access resources.

  • Windows Authentication with Impersonation with Fixed Authentication . With this approach, you impersonate a fixed Windows account to access resources using a specific identity. In Windows Server 2003, you should avoid this imitation; instead, use your own application pool with a custom service identifier.

According to the documentation, you can get a token of an authenticated Windows user.

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

If something is wrong, check your impersonation application according to MSDN documentation. How to use Windows Authentication in ASP.NET 2.0

See ScottGu's Recipe: Enabling Windows Authentication in an ASP.NET Intranet Web Application

+1
source

This is the code segment that I used in my ASP.NET MVC application not so long ago, it helped me, I don’t know if it will help you, but you can 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

Note that I also requested another database in this extract, ignoring all Linq statements. The DirectoryEntry , DirectorySearcher and SearchResult classes should help you with what you need.

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

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

0
source

I would try:

var i = Environment.CurrentUser;

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

-1
source

Source: https://habr.com/ru/post/915677/


All Articles