0

I am using the following to retrieve a user's email address on Windows which works for me and most of our clients, but one client is running into an error for multiple users.

var email = UserPrincipal.Current.EmailAddress;

The error: "The specified directory service attribute or value does not exist."

We have verified the correct email is populated in the "mail" attribute on the user's AD object.

I have researched the error and found multiple sources stating this error is likely caused by insufficient active directory permissions, but I have been unable to track down what specifically we need to change.

For testing, I have been using the follow in PowerShell, and the users experiencing the issue get the same error. When I run the commands in PowerShell it returns my email address as expected:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
[System.DirectoryServices.AccountManagement.UserPrincipal]::Current.EmailAddress

A code change is not possible, so I am wondering what, if any changes we could make to active directory settings that would allow this code to run without error?

cfitzer
  • 108
  • 1
  • 2
  • 9

1 Answers1

1

This isn't necessarily a solution, but additional troubleshooting. Try doing this in PowerShell for one of the affected users:

$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
$user = [ADSI]"LDAP://<SID=$sid>"
$user.RefreshCache("mail")
$user.mail

[ADSI] is a type accelerator for DirectoryEntry, which is what UserPrincipal uses behind the scenes. I'm not a fan of using UserPrincipal (or anything in the AccountManagement namespace) because it hides a lot of the details from you. You have less control of what it's requesting from the server, and thus performance too.

When you create a UserPrincipal object, it goes out to AD and loads a bunch of the user's attributes. I suspect that it might not even be the mail attribute that it's complaining about. So using this code will narrow that down. It will load only the mail attribute and nothing else (that's what RefreshCache() does).

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • This was helpful in verifying the user's mail attribute was set correctly, but we still do not know which permissions/settings are causing UserPrincipal.Current.EmailAddress call to fail. – cfitzer Feb 04 '22 at 14:36
  • The quickest way to figure it out is to debug the .NET source code, which can be done in .NET Core now. If you're able to create a simple .NET Core project that replicates the issue, and debug in Visual Studio following [the steps here](https://stackoverflow.com/a/55644394/1202807), you can stop at the exception within the .NET source and examine the local variables and figure out which attribute it's complaining about (hopefully). – Gabriel Luci Feb 04 '22 at 17:02