どのように私は、ユーザーがメンバーであるすべてのロール(グループ)を取得することができますか?
-
11-09-2019 - |
質問
明示的WindowsPrincipal.IsInRole
法により確認することなく、Windowsの認証されたユーザがあるロールのリストを取得する方法はありますか?
解決
WindowsPrincipal.IsInRole
だけチェック。 Windowsグループはの役割です。あなたは、ユーザーがWindowsIdentity.Groups
財産からのメンバーであるグループのリストを取得することができます。
あなたはWindowsIdentity
からWindowsPrincipal
を取得することができます:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
か、WindowsIdentityのファクトリメソッドからそれを得ることができます:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdenity.Groups
は、ちょうどあなたのグループのSIDを与えるIdentityReference
のコレクションです。あなたはグループ名が必要な場合は、IdentityReference
にNTAccount
を翻訳して値を取得する必要があります。
var groupNames = from id in identity.Groups
select id.Translate(typeof(NTAccount)).Value;
他のヒント
編集:ジョシュはそれに私を打ち負かします! :)
これを試してみてください。
using System;
using System.Security.Principal;
namespace ConsoleApplication5
{
internal class Program
{
private static void Main(string[] args)
{
var identity = WindowsIdentity.GetCurrent();
foreach (var groupId in identity.Groups)
{
var group = groupId.Translate(typeof (NTAccount));
Console.WriteLine(group);
}
}
}
}
あなたがドメインサーバに接続されていない場合は、Translate
機能は、以下の例外The trust relationship between this workstation and the primary domain failed.
を投げることがあります。
しかし、グループのほとんどのために、それはOKになりますので、私は使用します:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
try {
IdentityReference grp = s.Translate(typeof (NTAccount));
groups.Add(grp.Value);
}
catch(Exception) { }
}
ASP.NET MVCのサイトでは、あなたはこのようにそれを行うことができます:
あなたのWeb.configファイルにこれを追加します。
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
そして、あなたは、ユーザーがメンバーであるすべてのWindowsグループを取得するためにRoles.GetRolesForUser()
を使用することができます。あなたはusing System.Web.Security
していることを確認します。