Return to Snippet

Revision: 59157
at August 21, 2012 15:39 by toLL


Initial Code
// get current user identity
WindowsIdentity id = WindowsIdentity.GetCurrent();
var useName = id.Name;
var authType = id.AuthenticationType;

// all user groups (1)
foreach (var group in id.Groups)
{
    // get SID of group
    Console.WriteLine(group.Value);
    // translate group SID to name
    Console.WriteLine(group.Translate(typeof(NTAccount)));
}

// all user groups (2 - better performance)
foreach (var group in id.Groups.Translate(typeof(NTAccount)))
{
    Console.WriteLine(group);
}


// convert to SID  (Security Identifier)
NTAccount account = new NTAccount(id.Name);
var sid = account.Translate(typeof(SecurityIdentifier)));


// get principal
WindowsPrincipal principal = new WindowsPrincipal(id);

// check if user is in role
// local admin
var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
var hasAdminRole = principal.IsInRole(localAdmins);
// Domain admin
var domainAdmin = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
var isDomainAdmin =  principal.IsInRole(domainAdmin));


// Principal permission
new PrincipalPermission(null, "Marketing").Demand(); // throws exception if user doesn't have Marketing role

// same but as attribute
[PrincipalPermission(SecurityAction.Demand, Role="Development Group")]
private static void DoDeveloperWork()
{
    Console.WriteLine("You are a developer");
}

Initial URL

                                

Initial Description
How to get users identity and principal in C#

Initial Title
C# User Identity / Principal

Initial Tags
c#

Initial Language
C#