3

I'd like to authenticate my users against our ActiveDirectory and then extend the user data with other data from database.

My code works if I set AuthenticationManagerBuilder.userDetailsService() OR AuthenticationManagerBuilder.authenticationProvider() but not both at the same time.

Thanks

@Configuration

protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsServiceImpl);
        String adUrl = "ldap:///";
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("", adUrl);

        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        auth.authenticationProvider(provider);
        System.out.println("setting userDetailsServiceImpl");

    }
}

UserDetailsServiceImpl class

@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
    System.out.println(arg0);
    User user = this.userRepository.findOneByUsername(arg0);
    System.out.println("i've found this user : " + user.getNames());
    if (user == null) {
        throw new UsernameNotFoundException(arg0);
    }
    return new org.springframework.security.core.userdetails.User(arg0, "",getAllPrivileges(user));
    }

    private List<GrantedAuthority> getAllPrivileges(User user) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    Hibernate.initialize(user.getUserPrivileges());
    System.out.println(user.getUserPrivileges().size() + " privileges have been found for " + user.getNames());
    for (UserPrivilege privilege : user.getUserPrivileges()) {
        authorities.add(new SimpleGrantedAuthority(privilege.getPrivilege().getCodename()));
    }
    authorities.stream().forEach(a -> System.out.println(a.toString()));
    return authorities;
    }
}
BenoitD
  • 525
  • 1
  • 6
  • 16

0 Answers0