Skip to content

AppDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal) works only once #31717

@marcselis

Description

@marcselis

Setting the PrincipalPolicy on the current AppDomain to WindowsPrincipal works only for the first thread being started. Any subsequent thread has Thread.CurrentPrincipal evaluated to NULL.

See the following example:

    internal static class Program 
    {
        private static void Main()
        {
            // Set the principal policy to WindowsPrincipal.
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            
            // All threads should now have a Windows principal
            // according to the documentation on https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.setprincipalpolicy?view=netcore-3.1
            // Works here.
            var t = new Thread(PrintPrincipalInformation);
            t.Start();
            t.Join();

            //But doesn't work here anymore
            t = new Thread(PrintPrincipalInformation);
            t.Start();
            t.Join();

            // Create a principal to use for new threads.
            IIdentity identity = new GenericIdentity("NewUser");
            IPrincipal principal = new GenericPrincipal(identity, null);
            AppDomain.CurrentDomain.SetThreadPrincipal(principal);
            
            // Should create a new thread with the principal created above, 
            // according to the documentation here: https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.setthreadprincipal?view=netcore-3.1
            // Also doesn't work.
            t = new Thread(PrintPrincipalInformation);
            t.Start();
            t.Join();
        
            // Wait for user input before terminating.
            Console.ReadLine();
        }

        static void PrintPrincipalInformation()
        {
            var curPrincipal = Thread.CurrentPrincipal;
            if(curPrincipal != null)
            {
                Console.WriteLine("Type: " + curPrincipal.GetType().Name);
                Console.WriteLine("Name: " + curPrincipal.Identity.Name);
                Console.WriteLine("Authenticated: " +
                                  curPrincipal.Identity.IsAuthenticated);
                Console.WriteLine();
                return;
            }
            Console.WriteLine("Thread.CurrentPrincipal is NULL");
        }
    }

.NET Core Runtime 3.1.1
.NET Core SDK 3.1.101

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions