/ Published in: C#

How to get users identity and principal in C#
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// 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 } // all user groups (2 - better performance) { Console.WriteLine(group); } // convert to SID (Security Identifier) // get principal // check if user is in role // local admin 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"); }
Comments
