简体   繁体   中英

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. 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". 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; 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 .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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