我想针对ActiveDirectory对用户进行身份验证,然后使用数据库中的其他数据扩展用户数据。
如果我设置AuthenticationManagerBuilder.userDetailsService()或AuthenticationManagerBuilder.authenticationProvider()但我的代码可以同时运行。
谢谢
@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类
@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;
}
}