Getting UserPrincipal with Windows Authentication and Anonymous Authentication

The following code only works if IIS only includes Windows authentication for local users on our network.

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName); return up; } 

Otherwise, this is an exception:

[ArgumentException: search parameter (objectcategory = user) (objectclass = user) (| (userPrincipalName =) (distinctName =) (name =))) is invalid.] System.DirectoryServices.ResultsEnumerator.MoveNext () +434305 System.DirectoryServices.SearchResultCollection .get_InnerList () +282 System.DirectoryServices.SearchResultCollection.get_Count () +9 System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper (type mainType, String urnScheme, String urnValue, DateHentamelemetource reference ADStoreCtx.FindPrincipalByIdentRef (type mainType, String urnScheme, String urnValue, DateTime referenceDate) +85 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper (context PrincipalContext, type typeTyTimeDameTameTameTimeTerminalDataTameValue, IdentityTimeTerminalDefault .AccountManagement.UserPrincipal. FindByIdentity (PrincipalContext context, String identityValue) +95 WebApplication1.Index.GetUserPrincipal (String userName) in C: \ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs: 38 WebApplication1.Index. Page_Load (object sender, EventArgs e) in C: \ Users \ xxx \ Documents \ Visual Studio 2010 \ Projects \ WebApplication1 \ WebApplication1 \ Index.aspx.cs: 19 System.Web.Util.CalliHelper.EventArgFunctionCaller (IntPtr fp, Object o , Object t, EventArgs e) +25 System.Web.UI.Control.LoadRecursive () +71 System.Web.UI.Page.ProcessRequestMain (Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064

Is there a way to get this to work to get our local UserPrincipal users when Windows and anonymous authentication are turned on ?

+4
source share
2 answers

userName should be an empty string (or some other way, entirely consisting of spaces), and, apparently, it is not checked using FindByIdentity .

+1
source

Not sure how you found FindByIdentity to work, since I thought you also needed to specify the type of authentication? i.e:

 UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName); 

In any case, impersonation may work if you force it. So, before this piece of code, use the following:

 // This will impersonate the logged in user in order to get whichever username you require GIVEN the logged in user has AD read/querying rights. System.Web.HttpContext.Current.Request.LogonUserIdentity.Impersonate(); using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName); return up; } 
0
source

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


All Articles