كيف يمكنني استرجاع جميع الأدوار (مجموعات) المستخدم هو عضو؟
-
11-09-2019 - |
سؤال
هل هناك طريقة للحصول على قائمة بالأدوار يوجد مستخدم Windows مصادق عليه، دون فحص صراحة من قبل WindowsPrincipal.IsInRole
طريقة؟
المحلول
WindowsPrincipal.IsInRole
فقط يتحقق إذا كان المستخدم عضوا في المجموعة بهذا الاسم؛ مجموعة ويندوز هو دور. يمكنك الحصول على قائمة بالمجموعات التي يعد المستخدم عضوا من WindowsIdentity.Groups
خاصية.
يمكنك الحصول WindowsIdentity
منك WindowsPrincipal
:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
أو يمكنك الحصول عليها من طريقة المصنع على WindowsInidentity:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdenity.Groups
هي مجموعة من IdentityReference
الذي يمنحك فقط SID من المجموعة. إذا كنت بحاجة إلى أسماء المجموعة، فستحتاج إلى ترجمة IdentityReference
في an. 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.
ولكن بالنسبة لمعظم المجموعات، سيكون على ما يرام، لذلك يمكنني استخدام:
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>
ثم يمكنك استخدام Roles.GetRolesForUser()
للحصول على جميع مجموعات Windows التي يكون المستخدم عضوا في. تأكد من أنك using System.Web.Security
.