Thread.CurrentPrincipal Property

Definition

Gets or sets the thread's current principal (for role-based security).

C#
public static System.Security.Principal.IPrincipal? CurrentPrincipal { get; set; }
C#
public static System.Security.Principal.IPrincipal CurrentPrincipal { get; set; }

Property Value

An IPrincipal value representing the security context.

Exceptions

The caller does not have the permission required to set the principal.

Examples

The following code example shows how to set and retrieve the principal of a thread.

C#
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;

class Principal
{
    static void Main()
    {
        string[] rolesArray = {"managers", "executives"};
        try
        {
            // Set the principal to a new generic principal.
            Thread.CurrentPrincipal = 
                new GenericPrincipal(new GenericIdentity(
                "Bob", "Passport"), rolesArray);
        }
        catch(SecurityException secureException)
        {
            Console.WriteLine("{0}: Permission to set Principal " +
                "is denied.", secureException.GetType().Name);
        }

        IPrincipal threadPrincipal = Thread.CurrentPrincipal;
        Console.WriteLine("Name: {0}\nIsAuthenticated: {1}" +
            "\nAuthenticationType: {2}", 
            threadPrincipal.Identity.Name, 
            threadPrincipal.Identity.IsAuthenticated,
            threadPrincipal.Identity.AuthenticationType);
    }
}

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1