Identity
The System.Security.Principal namespace provides classes for representing the identity and principal of a user. These classes are fundamental for implementing security checks in .NET applications running on Windows.
Overview
Classes
Sample Code
References
What is Identity?
Identity represents the unique identifier for a security principal. In Windows, the most common representation is a WindowsIdentity object which encapsulates the user’s SID, name, and authentication type.
- Retrieving the current user’s identity
- Impersonation of another user
- Working with authentication tokens
Key Classes
| Class | Description |
|---|---|
WindowsIdentity | Represents a Windows user. |
WindowsPrincipal | Encapsulates identity with role-based checks. |
GenericIdentity | Provides a basic implementation for custom authentication. |
GenericPrincipal | Combines a generic identity with role membership. |
Getting Current User Identity (C#)
using System;
using System.Security.Principal;
class Program
{
static void Main()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
Console.WriteLine($"User: {identity.Name}");
Console.WriteLine($"Auth Type: {identity.AuthenticationType}");
Console.WriteLine($"Is Admin: {new WindowsPrincipal(identity)
.IsInRole(WindowsBuiltInRole.Administrator)}");
}
}
Run the snippet to view details about the current Windows user.