开发者

Thread.CurrentPrincipal in .NET console application

开发者 https://www.devze.com 2023-01-30 08:29 出处:网络
Here is a trivial console application that i run in command prompt: using System; using System.Threading;

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 'GenericPr开发者_JAVA技巧incipal' 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)?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消