Log in through active directory

164 views Asked by At

I want to create LogIn button through Active Directory. So i have an idea to take Name logged user(Windows) from his Domain:

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

and then take Group for Login above:

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

then something like:

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

I think my 'getting group' is wrong. How can I do it? I don't know how to exactly search for one or two groups where User is assigned. What about when user is assigned to many Groups?

2

There are 2 answers

9
Pankaj On BEST ANSWER

Here is the point to use windows identity to authorize login.

1) Get the windows identity of user.

2) Use Windows identity object to get the other information like name and group. use group name to validate user request. Hope this will help you. Please write in comment in you have any questions.

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");
        }
0
Kafus On

Ok, i got this. Thanks for 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");
    }