我正在使用LDAP和JSON Web令牌(JWT)为我的Web服务构建安全层。这个想法是:
Basic
对该用户进行身份验证。因此,对于每个需要验证的请求,用户必须包括用户名/密码或令牌。
这是我的LDAP配置:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.ldif("classpath:test-server.ldif")
.root("dc=springframework,dc=org")
.port(8389)
.and()
.passwordCompare()
.passwordEncoder(passwordEncoder())
.passwordAttribute("userPassword");
// @formatter:on
// Do I need this? Why?
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
从上面的配置中可以看到,我使用了自定义UserDetailsService
。这是实现:
@Service
public class LdapUserService implements UserDetailsService {
private LdapUserRepository ldapUserRepository;
@Autowired
public LdapUserService(LdapUserRepository ldapUserRepository) {
this.ldapUserRepository = ldapUserRepository;
}
// When is this function called?
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LdapUser ldapUser = ldapUserRepository.findByUsername(username);
if (ldapUser == null) {
throw new UsernameNotFoundException(username);
}
// How can I access this return value somewhere else?
return new User(ldapUser.getUsername(), ldapUser.getPassword(), new ArrayList<>());
}
}
一切正常。但是,我不完全了解整个设置。
UserDetailsService
吗?loadUserByUsername()
从未被呼叫。能请您举例说明一下吗?谢谢您的帮助。