Search code examples
model-view-controlleractive-directorymembership-provider

active directory mvc without membership


I need to implement a mixed mode authentication both form and windows authentication in my Application using MVC 5

That means I need to implement Active directory Authentication without using ASP.NET membership provider.


Solution

  • Seems like you want to use active directory user as ASP.NET Identity user.. Prepare a method for UserLogin info(for adding to ASPNET Idenity)

        private UserLoginInfo GetWindowsLoginInfo(string userId, string password)
        {
            string result = IsValidADUser(userId, password);
            return result != "" ? new UserLoginInfo("Windows", result) : null;
        }
    

    and create a method for validating against active directory

    private string IsValidADUser(string userName, string password)
        {
    
            String adServerName = "LDAP://<<your LDAP String>>";
            var sid = "";
    
        try
        {
            var directoryEntry = new DirectoryEntry();
            if (!string.IsNullOrEmpty(adServerName))
            {
                directoryEntry.Path = adServerName;
                directoryEntry.Username = userName;
                                directoryEntry.Password = password;
                directoryEntry.AuthenticationType = AuthenticationTypes.Secure;
            }
            else
            {
                throw new Exception("Invalid AD");
            }
            if (directoryEntry.NativeObject != null)
            {
                // Verify the user is locked or not
                DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
                                searcher.Filter = "(SAMAccountName=" + userName + ")";
                searcher.CacheResults = false;
                SearchResult result = searcher.FindOne();
    
                if (result == null || result.Properties["lockoutTime"][0].ToString() != "0")
                {
                    throw new Exception("User Account is locked");
                }
                else
                {
                    var sidInBytes = (byte[])result.Properties["objectSid"][0];
                    sid = new SecurityIdentifier(sidInBytes, 0).ToString();
                    //isValidUser = true;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("AD:" + ex.Message);
        }
        return sid;
    }