I've got a WebSite and API hosted on the same server on IIS. In the API (.NET) I need to acquire list of AD Groups that the user that is using the website belongs to. It works locally (Postman calls to API on IIS Express) but it doesn't when ran on our server. Code for acquiring AD Groups is this:
string[] output = null;
string username = GetUserName();
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(ctx, username))
{
if (user != null)
{
output = user.GetGroups() //this returns a collection of principal objects
.Select(x => x.SamAccountName) // select the name. you may change this to choose the display name or whatever you want
.ToArray(); // convert to string array
}
}
Username is recognized correctly and the same value is passed on localhost and on server, so that's not an issue. Line:
using (var user = UserPrincipal.FindByIdentity(ctx, username))
returns an Exception:
An exception of type 'System.DirectoryServices.DirectoryServicesCOMException' occurred in System.DirectoryServices.AccountManagement.dll but was not handled in user code
It's probably something in IIS settings but I can't figure out what. I tried setting Identity of DefaultAppPool (ApplicationPool that Web and API is assigned to) to NetworkService, but it didn't help.