16

Here is a trivial console application that i run in command prompt:

using System;
using System.Threading;
namespace Test
{
    internal class Runner
    {
        [STAThread]
        static void Main(string[] args)
        {
            Console.WriteLine(Thread.CurrentPrincipal.GetType().Name);
            Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
        }
    }
}

The output is 'GenericPrincipal' and empty string as identity name. Why the run-time constructs GenericPrincipal instead of WindowsPrincipal? How do i force it to construct WindowsPrincipal from the security token of the starting process (cmd.exe in my case)?

UserControl
  • 14,766
  • 20
  • 100
  • 187
  • What do you get when you query `WindowsIdentity current = WindowsIdentity.GetCurrent();` ?? – marc_s Dec 12 '10 at 14:01
  • 1
    It returns my current windows identity as i expect. So is it my responsibility to construct and attach the principal? Or there is a way to specify it in the configuration file just like security setting in ASP.NET or WCF application? – UserControl Dec 12 '10 at 14:11

1 Answers1

36

You have to tell your app what PrincipalPolicy to use. You would add

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

making your code look like:

using System;
using System.Threading;
using System.Security.Principal;

namespace Test
{
    internal class Runner
    {
        [STAThread]
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            Console.WriteLine(Thread.CurrentPrincipal.GetType().Name);
            Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
        }
    }
}

See http://msdn.microsoft.com/en-us/library/system.appdomain.setprincipalpolicy.aspx

weloytty
  • 5,808
  • 5
  • 28
  • 35