Search code examples
springspring-securityactive-directoryldap

search filter with userUserPrincipalName always Active Directory authentication failed: Supplied password was invalid


I have set samAccountName: mti and set [email protected]. When I use sameAccountName everthing works correct, but with userPrincipal not. I want to have two options in same time, but first i'm trying only with userPricipalName.

    @Bean
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(environmentsVariables.LDAP_DOMAIN, environmentsVariables.LDAP_PROVIDER_URL);
//        provider.setSearchFilter("(&(objectClass=user)(samAccountName={1}))");
        provider.setSearchFilter("(&(objectClass=user)(userPrincipalName={0}))");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        provider.setUserDetailsContextMapper(userDetailsContextMapper());
        return provider;
    }

Solution

  • I want to have two options in same time

    LDAP allows boolean operators to try different inputs. For example, you can do:

    provider.setSearchFilter("(|" +
        "(&(objectClass=user)(userPrincipalName={0}))" +
        "(&(objectClass=user)(samAccountName={1}))" +
    ")");
    

    sameAccountName everthing works correct, but with userPrincipal not

    By default, Spring Security will take the provided username and append the domain to make the bind principal. So, if the user enter's mti as the username, {0} (userPrincipalName1) will be [email protected] and {1} (samAccountName) will be mti. This may be the reason that it's not working for samAccountName.