WindowsPrincipal Class

Represents the principal that is authenticated and authorized to perform actions on a Windows system. This class represents a Windows user and provides information about the user's identity and roles.

Namespace:

System.Security.Principal

Assembly:

System.Security.dll

Syntax

public sealed WindowsPrincipal : IPrincipal

Remarks

The WindowsPrincipal class represents a Windows user identity. When you create an instance of this class, you can pass a WindowsIdentity object to represent the user. The WindowsPrincipal then provides access to the user's Windows security token, allowing you to check for group memberships and other security-related information.

This class is commonly used in ASP.NET applications and other .NET applications to determine the security context of the current user and to enforce authorization rules.

Constructors

WindowsPrincipal(WindowsIdentity identity)

Initializes a new instance of the WindowsPrincipal class with the specified WindowsIdentity.

public WindowsPrincipal(WindowsIdentity identity);

Properties

Identity

Gets the IIdentity associated with the current principal.

public IIdentity Identity { get; }

Methods

IsInRole(string role)

Determines whether the current principal is a member of the specified role. For WindowsPrincipal, this method checks for membership in Windows groups.

public bool IsInRole(string role);

Parameters

Returns

true if the principal is a member of the specified role; otherwise, false.

IsInRole(WindowsBuiltInRole role)

Determines whether the current principal is a member of the specified Windows built-in role.

public bool IsInRole(WindowsBuiltInRole role);

Parameters

Returns

true if the principal is a member of the specified role; otherwise, false.

Example

Checking user role membership in C#:

using System.Security.Principal;

public class SecurityHelper
{
    public static bool IsUserInAdminRole()
    {
        // Get the current Windows identity
        WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

        // Create a WindowsPrincipal from the identity
        WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

        // Check if the user is in the "Administrators" role
        return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    public static bool IsUserInSpecificGroup(string groupName)
    {
        WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
        WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

        // Check for membership in a custom group name
        return windowsPrincipal.IsInRole(groupName);
    }
}

Requirements