In the. NET security model, the iprincipal. isinrole method is used to determine the user group role. This method requires a string parameter. The windowsprincipal type (Inheritance and iprincipal) also provides integer RID and windowsbuiltinrole to determine user roles. Therefore, the same role has multiple judgment methods.
For example, determine whether the user is builtin \ Users and nt authority \ Authenticated Users:
// + Using system. Security. Principal;
VaRWinidentity= Windowsidentity.Getcurrent ();
VaRWinprincipal= New Windowsprincipal(Winidentity );
// Builtin \ Users
Console.Writeline (winprincipal.Isinrole (Windowsbuiltinrole.User ));
Console.Writeline (winprincipal.Isinrole ("Users"));
Console.Writeline (winprincipal.Isinrole ("Builtin \ Users"));
// Nt authority \ Authenticated Users
Console.Writeline (winprincipal.Isinrole ("Authenticated Users"));
Console.Writeline (winprincipal.Isinrole ("Nt authority \ Authenticated Users"));
True is returned for all outputs.
Another method is to use the Groups option of windowsidentity and convert all identifierreferences to securityidentifier. Because windowsidentity. Groups returns the identityreferencecollection object. Finally, securityidentifier. iswellknown and wellknowsidtype enumeration are used to determine whether it is a predefined Sid.
Code:
// + Using system. Security. Principal;
VaRWinidentity= Windowsidentity.Getcurrent ();
VaRSIDS=Winidentity.Groups.Select (I=>(Securityidentifier) I.Translate (Typeof(Securityidentifier)));
console . writeline (SIDS . Any (I => I . iswellknown ( wellknownsidtype . builtinuserssid);
Console.Writeline (SIDS.Any (I=>I.Iswellknown (Wellknownsidtype.Ntlmauthenticationsid )));
Finally, the preceding method can be modified to obtain another method: manually determine by Sid. For the pre-defined Sid in windows, see http://support.microsoft.com/kb/243330.
Code:
// + Using system. Security. Principal;
var winidentity = windowsidentity . getcurrent ();
VaRSIDS=Winidentity.Groups.Select (I=>(Securityidentifier) I.Translate (Typeof(Securityidentifier)));
// S-1-5-32-545: Is the SID of users
Console.Writeline (SIDS.Contains (New Securityidentifier(S-1-5-32-545")));
// S-1-5-11: Sid of authenticated users
Console.Writeline (SIDS.Contains (New Securityidentifier(S-1-5-11")));