通过活动目录登录

本文关键字:登录 活动 过活 | 更新日期: 2023-09-27 17:54:09

我想通过Active Directory创建登录按钮。所以我有一个想法,从他的域名取名称登录用户(Windows):

 string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

,然后在上面取Group for Login:

 string Group = System.Security.Principal.WindowsIdentity.GetCurrent().Groups.ToString(); // <---I think this is wrong ? 
 string allowedGroup = "Admins";  

然后像这样:

if(Name == string.Empty)
 {
    MessageBox.Show("Your Name in domain doesn't exist");
 }
if(Group.ToString() != allowedGroup)
 {
    MessageBox.Show("You don't have permissions to log in");
 }
else
 {
    MessageBox.Show("Hello");
 }

我认为我的"得到组"是错误的。我该怎么做呢?我不知道如何准确地搜索一个或两个组,其中用户被分配。如果用户被分配到多个组,情况会怎样?

通过活动目录登录

这就是使用windows身份来授权登录的要点。

1)获取用户的windows身份。

2)使用Windows identity对象获取其他信息,如名称和组。使用组名验证用户请求。希望这对你有帮助。如果你有任何问题,请在评论中留言。

System.Security.Principal.WindowsIdentity WI =  System.Security.Principal.WindowsIdentity.GetCurrent();
        string sUserName = WI.Name;
        bool bAuthorized = false;
        string allowedGroup = "Admins";
        IdentityReferenceCollection irc = WI.Groups;
        foreach (IdentityReference ir in irc)
        {
            if(ir.Translate(typeof(NTAccount)).Value == allowedGroup)
            {
                bAuthorized = true;
                break;
            }
        }
        if(string.IsNullOrEmpty(sUserName))
        {
            MessageBox.Show("Your Name in domain doesn't exist");
        }
        if(bAuthorized == false)
        {
            MessageBox.Show("You don't have permissions to log in");
        }
        else
        {
            MessageBox.Show("Hello");
        }

好的,我知道了。谢谢Pankaj。

    System.Security.Principal.WindowsIdentity WI = System.Security.Principal.WindowsIdentity.GetCurrent();
    string sUserName = WI.Name;
    bool bAuthorized = false;
    string allowedGroup = "Admins";
    IdentityReferenceCollection irc = WI.Groups;
    foreach (IdentityReference ir in irc)
    {
      NTAccount accInfo = (NTAccount)ir.Translate(typeof(NTAccount));
        if (accInfo.Value == allowedGroup)
        {
           bAuthorized = true;
           break;
        }
    }
    if(string.IsNullOrEmpty(sUserName))
    {
        MessageBox.Show("Your Name in domain doesn't exist");
    }
    if(bAuthorized == false)
    {
        MessageBox.Show("You don't have permissions to log in");
    }
    else
    {
        MessageBox.Show("Hello");
    }