简体   繁体   English

使用存储在sql数据库中的AD组名称授权C#应用程序中的用户

[英]Using AD group names stored in sql database for authorizing users in C# app

I have been sitting for this question so long and could not find an answer for it anywhere, however I know many companies are using what I want to do so I decided to put it on here. 我一直在讨论这个问题很久了,在任何地方都找不到答案,但是我知道许多公司都在使用我想做的事情,所以我决定将其放在此处。

What I would like to do is: 我想做的是:

  • Store Windows users and/or AD groups in my database, assigning them to roles in the application. 将Windows用户和/或AD组存储在我的数据库中,并将其分配给应用程序中的角色。 Of course these roles will be linked in my database to the user or group. 当然,这些角色将在我的数据库中链接到用户或组。
  • For a user, this is easy because you already have the user name when he/she logs in. 对于用户而言,这很容易,因为您在登录时已经有了用户名。
  • I want to find out in my app if the user belongs to any of the AD groups stored in my database and assign his/her permissions accordingly. 我想在我的应用程序中查找用户是否属于存储在数据库中的任何广告组,并相应地分配其权限。

So here's an example: 所以这是一个例子:

I know my user has an entry in my database user/groups table: I know he is in the AD group called "MyAppGroup\\MyDomain". 我知道我的用户在我的数据库用户/组表中有一个条目:我知道他在AD组中,名为“ MyAppGroup \\ MyDomain”。 What is the easiest way to find out from my list of groups in the database to find out a user is in it? 从数据库的组列表中找出用户所在的最简单方法是什么?

As mentioned in the comments, the data you are looking for is already stored in Active Directory; 如注释中所述,您要查找的数据已经存储在Active Directory中;例如, you don't need to add it to your database at all. 您根本不需要将其添加到数据库中。

You can query AD (including group membership and a ton of other data) using the System.DirectoryServices.AccountManagement API . 您可以使用System.DirectoryServices.AccountManagement API查询AD(包括组成员身份和大量其他数据)。

Here's a small example of how to retrieve the groups that a user is a member of: 这是一个有关如何检索用户所属的组的小示例:

using System.DirectoryServices.AccountManagement;

// ...

public List<string> GetGroupsForUser(string domain, string ou, string samAccountName)
{
    var groups = new List<string>(); 

    using (var principalContext = new PrincipalContext(ContextType.Domain, domain, ou))
    using (var userPrinicpal = UserPrincipal.FindByIdentity(principalContext, 
        IdentityType.SamAccountName, samAccountName))
    {
        if (userPrinicpal == null)
            return null;

        foreach (var securityGroup in userPrinicpal.GetAuthorizationGroups())
            groups.Add(securityGroup.DisplayName);
    }

    return groups;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM