Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.CurrentPrincipal in .NET console application

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)?

like image 248
UserControl Avatar asked Dec 12 '10 13:12

UserControl


People also ask

What is thread CurrentPrincipal in C#?

Thread. CurrentPrincipal is the way . NET applications represent the identity of the user or service account running the process. It can hold one or more identities and allows the application to check if the principal is in a role through the IsInRole method. Most authentication libraries in .

Which property determines the current user in the security context?

CurrentPrincipal property to an object that implements the IPrincipal interface to enable custom authentication. In most project types, this property gets and sets the thread's current principal.


1 Answers

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

like image 51
weloytty Avatar answered Oct 02 '22 12:10

weloytty