Winform user authorization via active directory

13,302

Since your computer is not joined to domain at all, we cannot use WindowsIdentity or WindowsPrincipal and then check its IsInRole() method. The IsInRole() method works only if your computer is joined to the domain and it's using your domain machine account to do S4USelf.

You cannot use LogonUser approach too because your computer won't let you create a logon session from an untrusted forest.

I think we can only query the Active Directory directly to get the information we want. The code in your posted Microsoft KB does not work very well as far as I can tell. It's trying to query from memberOf attribute. The group information is not always available from the memberOf attributes.

I just wrote an IsInRole() function using AccountManagement. I guess this is what you want. The IsInRole() function will call a recursive function IsInGroup() to find out all the groups the user belongs to.

private bool IsInRole(string domain, string username, string password, string role)
{
    using (var context = new PrincipalContext(ContextType.Domain, domain, username, password))
    {
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, role);
        UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
        return IsInGroup(user, group);
    }
}

private bool IsInGroup(Principal principal, GroupPrincipal group )
{
    if (principal.IsMemberOf(group))
        return true;

    foreach (var g in principal.GetGroups())
    {
        if (IsInGroup(g, group))
            return true;
    }

    return false;
}

To use this IsInRole() function, you need to provide your domain name and domain credentials. If the username and password provided are wrong, you will get an exception.

You need .NET 3.5 SP1 to use AccountManagement API. Also, you may like to pay attention to this hotfix. The AccountManagement API got some bugs if running in some environment. You may need to apply the hotfix.

Share:
13,302

Related videos on Youtube

Saif Khan
Author by

Saif Khan

Updated on June 04, 2022

Comments

  • Saif Khan
    Saif Khan almost 2 years

    I have a situation where I am using the following code to verify user membership in AD before executing tasks in my app

    using System.Security.Principal;
    WindowsIdentity  identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole("someGroup");
    

    The above code works fine for machines on my domain, however I do have some machines which are not on my domain on which I have the WINFORM application installed. How can I verify the user membership in AD?

    Edit - is there a way to prompt the windows login?

    • Harvey Kwok
      Harvey Kwok about 13 years
      Any comment on my proposed answer? Does it work for you?