.NET(C#):通過WindowsPrincipal和WindowsIdentity.Groups判斷使用者組

來源:互聯網
上載者:User

通常.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")));

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.