dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.12k stars 4.7k forks source link

UserPrincipal.Current throws InvalidCastException in User.FindByIdentity #51744

Open Identifier opened 3 years ago

Identifier commented 3 years ago

In a .NET 5 Console app as follows:

using System;
using System.DirectoryServices.AccountManagement;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var currentUserPrincipal = UserPrincipal.Current; // Throws InvalidCastException

            Console.WriteLine($"Hello, {currentUserPrincipal.UserPrincipalName ?? "null"}!");
        }
    }
}

UserPrincipal.Current calls UserPrincipal.FindByIdentity, which throws an InvalidCastException when trying to cast a GroupPrincipal to a UserPrincipal:

 System.InvalidCastException: Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
   at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
   at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
   at ConsoleApp1.Program.Main(String[] args) in C:\Source\ConsoleApp1\ConsoleApp1\Program.cs:line 12

The specific line is here:

https://github.com/dotnet/runtime/blob/4ab71ae44b78a6139739798f8bba090d520bfc1f/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs#L271

Apparently FindByIdentityWithType is returning a GroupPrincipal even though we wanted a UserPrincipal. This is running on a Windows 10 machine joined to Microsoft Azure AD (normal MSFT employee setup).

joperezr commented 3 years ago

@Identifier thanks for logging the issue, this seems like an issue and we should have an if check instead of a hard cast there.

iSazonov commented 2 months ago

Root of the case is not the cast. In the OP example we explicitly ask UserPrincipal but the method return something else. After some investigations I believe AccountManagement API doesn't support AzureAD/Entra accounts at all. What would ContentType be for AzureAD/Entra accounts?

iSazonov commented 2 months ago

Duplicate #30408