C# User Identity / Principal


/ Published in: C#
Save to your folder(s)

How to get users identity and principal in C#


Copy this code and paste it in your HTML
  1. // get current user identity
  2. WindowsIdentity id = WindowsIdentity.GetCurrent();
  3. var useName = id.Name;
  4. var authType = id.AuthenticationType;
  5.  
  6. // all user groups (1)
  7. foreach (var group in id.Groups)
  8. {
  9. // get SID of group
  10. Console.WriteLine(group.Value);
  11. // translate group SID to name
  12. Console.WriteLine(group.Translate(typeof(NTAccount)));
  13. }
  14.  
  15. // all user groups (2 - better performance)
  16. foreach (var group in id.Groups.Translate(typeof(NTAccount)))
  17. {
  18. Console.WriteLine(group);
  19. }
  20.  
  21.  
  22. // convert to SID (Security Identifier)
  23. NTAccount account = new NTAccount(id.Name);
  24. var sid = account.Translate(typeof(SecurityIdentifier)));
  25.  
  26.  
  27. // get principal
  28. WindowsPrincipal principal = new WindowsPrincipal(id);
  29.  
  30. // check if user is in role
  31. // local admin
  32. var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
  33. var hasAdminRole = principal.IsInRole(localAdmins);
  34. // Domain admin
  35. var domainAdmin = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
  36. var isDomainAdmin = principal.IsInRole(domainAdmin));
  37.  
  38.  
  39. // Principal permission
  40. new PrincipalPermission(null, "Marketing").Demand(); // throws exception if user doesn't have Marketing role
  41.  
  42. // same but as attribute
  43. [PrincipalPermission(SecurityAction.Demand, Role="Development Group")]
  44. private static void DoDeveloperWork()
  45. {
  46. Console.WriteLine("You are a developer");
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.