どのように私は、ユーザーがメンバーであるすべてのロール(グループ)を取得することができますか?

StackOverflow https://stackoverflow.com/questions/762245

質問

明示的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のコレクションです。あなたはグループ名が必要な場合は、IdentityReferenceNTAccountを翻訳して値を取得する必要があります。

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していることを確認します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top