通常.NET安全模型中判斷使用者組角色使用IPrincipal.IsInRole方法,該方法需要一個字串參數。而WindowsPrincipal類型(繼承與IPrincipal)還提供了整數RID和WindowsBuiltInRole來判斷使用者角色。因此同一個角色有多種判斷方式。
比如判斷使用者是否是BUILTIN\Users和NT Authority\Authenticated Users:
//+ using System.Security.Principal;
var winIdentity = WindowsIdentity.GetCurrent();
var winPrincipal = 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。
另一種方法就是通過WindowsIdentity的Groups選項,然後把所有IdentifierReference轉換成SecurityIdentifier。因為WindowsIdentity.Groups返回IdentityReferenceCollection對象。最後用SecurityIdentifier.IsWellKnown和WellKnowSidType枚舉來判斷是否是預定義SID。
代碼:
//+ using System.Security.Principal;
var winIdentity = WindowsIdentity.GetCurrent();
var sids = 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)));
最後,上面的方法還可以另作修改便得到另一種方法:就是手動通過SID來判斷,對於Windows系統中預定義的SID,可以參考:http://support.microsoft.com/kb/243330。
代碼:
//+ using System.Security.Principal;
var winIdentity = WindowsIdentity.GetCurrent();
var sids = winIdentity.Groups.Select(i => (SecurityIdentifier)i.Translate(typeof(SecurityIdentifier)));
//S-1-5-32-545: 是Users的SID
Console.WriteLine(sids.Contains(new SecurityIdentifier("S-1-5-32-545")));
// S-1-5-11:Authenticated Users的SID
Console.WriteLine(sids.Contains(new SecurityIdentifier("S-1-5-11")));