首页 > 解决方案 > 使用 PrincipalContext 验证凭据并查找用户组

问题描述

我在 MVC Web 应用程序中使用 c# 代码来验证用户并查找特定用户所属的用户组列表,并使用以下代码

    try
    {
        List<string> user_groups= new  List<string>(); //save the groups the user belongs to 
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.com",model.Email,model.Password))      
        {
            bool valid=ctx.ValidateCredentials(model.Email, model.Password); //validate the user
            if(valid)
            {               
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, model.Email);
                if (user != null)
                {
                    // get the user's groups
                    var groups = user.GetAuthorizationGroups();
                    foreach (GroupPrincipal group in groups)
                    {
                        // save those groups to session for further processing after login
                        if ((bool)group.IsSecurityGroup)
                        {
                            user_groups.Add(group.Name);
                        }
                    }
                }
                _groups = string.Join(",", user_groups);
                ViewBag.Message = _groups;

            }
            else
            {
                ViewBag.Message = "Error while validating";
            }

            ctx.Dispose();
        }

    }
    catch (PrincipalServerDownException)
    {
        //If  server is down or some exception happends ,
        // ad_verification = false;
        ViewBag.Message = "Error at groups fetching as server is down ";
    }
    catch (Exception ex)
    {
        ViewBag.Message = "Error at groups fetching as "+ex.Message;
    }

我将它部署到服务器并尝试以 user1 身份登录,一切顺利代码验证用户凭据并返回 user1 所属的用户组列表
现在我在服务器上以 user2 身份登录,然后返回以下错误

   Error at groups fetching as Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.

看起来我仍然可以以 user1 身份登录,但对于所有其他用户,错误与上述相同。在本地 IIS 上进行测试时,没有此类问题 上述行在第二个用户之后中断的任何已知原因以及解决此问题的任何建议

标签: c#active-directoryldap

解决方案


您没有说哪一行引发了异常,但您可能不喜欢使用用户的凭据来提取所有数据。

如果您从加入同一域(或受信任域)的计算机运行此程序,则无需将凭据放在这里:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.com"))

ValidateCredentials()行将验证凭据,其他一切都将使用运行应用程序的凭据完成。

在旁注中,您不需要调用ctx.Dispose()何时ctx是您的using块的主题。的全部目的using是它会Dispose()在它离开using块后调用。看看文档


推荐阅读