Пользовательский фильтр аутентификации LDAP

У меня есть пользовательский класс CustomAuthenticationProvider для проверки подлинности, который выполняет проверку подлинности пользователя путем нажатия на удаленный сервер LDAP. Мне удалось создать и настроить пользовательский поставщик аутентификации, но у меня возникли проблемы с вызовом метода doAuthentication, который определен в SecurityConfiguration.

@Component 
public class CustomAuthenticationProvider implements AuthenticationProvider {
private final Logger log=LoggerFactory.getLogger(CustomAuthenticationProvider.class);

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (username == null) {
        throw new BadCredentialsException("User is not found");
    }

    if (password == null) {
        throw new BadCredentialsException("Password is not found");
    }

    try {
        LdapContextSource ldapContextSource = new LdapContextSource();
        ldapContextSource.setUrl("ldap://jnj.com:3268");
        ldapContextSource.setBase("dc=jnj,dc=com");
        ldapContextSource.setUserDn(username);
        ldapContextSource.setPassword(password);
        try {
            // initialize the context
            ldapContextSource.afterPropertiesSet();
        } catch (Exception e) {
            e.printStackTrace();
        }

        LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource);
        ldapTemplate.afterPropertiesSet();

       // ldapTemplate.setIgnorePartialResultException(true); // Active Directory doesn’t transparently handle referrals. This fixes that.
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("sAMAccountName", username));

        try {
            boolean authed = ldapTemplate.authenticate("", filter.toString(), password);
            log.debug("Auuthenticated : "+authed);
        } catch (org.springframework.ldap.AuthenticationException ee) {
//userDisplay.setText(“Invalid Username/Password”);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Collection<? extends GrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password, authorities);

     return  authenticationToken;
   // return new UsernamePasswordAuthenticationToken(username,password);

}



@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

Этот метод вызывается в SecurityConfiguration, мне нужно привязать этот метод к моему классу CustomAuthenticationProvider

 @Inject
public void configureGlobal(AuthenticationManagerBuilder auth) {
    try {
             auth.authenticationProvider(authProvider)
             .ldapAuthentication().userDetailsContextMapper(userDetailsContextMapper())
            .ldapAuthoritiesPopulator(ldapAuthoritiesPopulator()).userSearchBase(USER_SEARCH_BASE)
            .userSearchFilter(USER_SEARCH_FILTER).groupSearchBase(GROUP_SEARCH_BASE)
            .groupSearchFilter(GROUP_SEARCH_FILTER).contextSource(contextSource());

    } catch (Exception e) {
        throw new BeanInitializationException("Security configuration failed", e);
    }
}

Этот метод мне нужно вызвать для LDAP

 protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
        String username = auth.getName();
        String password = (String) auth.getCredentials();

        DirContext ctx = bindAsUser(username, password);

        try {
            return searchForUser(ctx, username);
        } catch (NamingException e) {
            log.error("Failed to locate directory entry for authenticated user: " + username, e);
            throw badCredentials(e);
        } finally {
            LdapUtils.closeContext(ctx);
        }
    }

0 ответов

Другие вопросы по тегам