Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LDAP Authentication with Asp.NET Identity

I trying impliment Active Directory authentication for my ASP.NET MVC application. I use System.DirectoryServices and during login find user in UserManager. If user not found I'm trying find user in Active Directory and if successful register user in asp.net mvc app with UserManager.CreateAsync().

    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel loginModel, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(loginModel.UserName, loginModel.Password);
            if (user != null)
            {
                await SignInAsync(user, loginModel.RememberMe);
                return RedirectToLocal(returnUrl);
            }

            string userFullName;
            if (AuthenticateActiveDirectoryUser("mydomain.local", loginModel.UserName, loginModel.Password, out userFullName))
            {
                var newUser = new ApplicationUser { UserName = loginModel.UserName, FullName = userFullName };
                var result = await UserManager.CreateAsync(newUser, loginModel.Password);                   

                if (result.Succeeded)
                {
                    await SignInAsync(newUser, loginModel.RememberMe);
                    return RedirectToLocal(returnUrl);
                }

                AddErrors(result);
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName or Password");
            }
        }

        return View(loginModel);
    }

    private bool AuthenticateActiveDirectoryUser(
        string domain,
        string username,
        string password,
        out string fullName)
    {
        fullName = string.Empty;

        var domainAndUsername = string.Format("{0}\\{1}", domain, username);
        var ldapPath = "";
        var entry = new DirectoryEntry(ldapPath, domainAndUsername, password);
        try
        {
            // Bind to the native AdsObject to force authentication.
            var obj = entry.NativeObject;
            var search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + username + ")" };
            search.PropertiesToLoad.Add("cn");
            var result = search.FindOne();
            if (result == null)
                return false;

            try
            {
                fullName = (string)result.Properties["cn"][0];
            }
            catch
            {
                fullName = string.Empty;
            }
        }
        catch (Exception ex)
        {
            return false;
        }

        return true;
    }

But in my implementation ignored cases if user change password in Active Directory account or AD Account was deleted. I can check it manually in my code, but maybe exists other ways in ASP.NET Identity to implement authentication by Active Directory user account?

like image 751
F_Z_14 Avatar asked Sep 09 '15 04:09

F_Z_14


People also ask

Can Active Directory users authentication via LDAP be implemented via Active Directory?

And as both ASP.NET and Active Directory have been around for a while, and given the fact that both come from the same vendor, one would expect that implementing Active Directory users authentication via LDAP in such a setup to be a well-known topic with detailed documentation, examples and a lot of tutorials available.

What is the use of LDAP password provider?

Provides LDAP password authentication for an existing ASP.NET Core Identity user store via an LDAP bind. I created this for a project I'm working on with a very basic need, so it is not an exchaustive provider by any means. LDAP password authentication via a custom UserManager against any existing UserManager/UserStore combination.

Does LDAP use NTLM authentication?

We will use an LDAP client which does not use NTLM authentication, to show that this can be done with any client and on any platform. At the end of this tutorial you will have an ASP.Net application capable of authenticating users against a directory, and displaying the credentials of the active user.

Is it possible to authenticate a user using ldapuserresourceownerpasswordvalidator?

This grant type is used to support legacy systems and is not recommended for new development. The code that you want to executed to authenticate a user is in LdapUserResourceOwnerPasswordValidator.cs and it should be executed if you pass the correct parameters to the token endpoint:


1 Answers

see if this can help u

    protected bool ActiveDirectoryLogin(string Username, string Password, string Domain)
{
    bool Success = false;
    //System.DirectoryServices.DirectoryEntry Entry =
    //    new System.DirectoryServices.DirectoryEntry("LDAP://***.**.**.**:389/cn=***-People,o=**,dc=**,dc=edu,dc=sa", "uid=" + Username + ",cn=***-People,o=***,dc=***,dc=edu,dc=sa", Password, AuthenticationTypes.None);

    System.DirectoryServices.DirectoryEntry Entry =
        new System.DirectoryServices.DirectoryEntry("LDAP://ldapmaster.***.edu.sa:389/cn=***-People,o=***,dc=***,dc=edu,dc=sa", "uid=" + Username + ",cn=***-People,o=***,dc=***,dc=edu,dc=sa", Password,AuthenticationTypes.None);

    //System.DirectoryServices.DirectoryEntry Entry =
    //    new   System.DirectoryServices.DirectoryEntry("LDAP://ldapmaster.***.edu.sa:389/cn=***-People,o=***,dc=***,dc=edu,dc=sa", Username , Password, AuthenticationTypes.None);

    System.DirectoryServices.DirectorySearcher Searcher = new System.DirectoryServices.DirectorySearcher(Entry);
            try
    {

        Object nat = Entry.NativeObject;
        Success = true;
//            System.DirectoryServices.SearchResult Results =     Searcher.FindOne();
//            Success = (Results != null);

    }
    catch (Exception e)
    {
        Success = false;
    }

    return Success;
}
like image 90
Shomaail Avatar answered Sep 28 '22 06:09

Shomaail