通过spring LDAP进行身份验证,并在数据库中进行额外的安

时间:2013-09-11 09:51:34

标签: spring authentication jdbc spring-security ldap

在LDAP身份验证之后,如果用户表中列出了用户ID,我想检查数据库。

我怎样才能做到这一点?我可以在Google上看到的只是通过LDAP进行身份验证以及在数据库上检索用户角色。

1 个答案:

答案 0 :(得分:3)

你必须改变让用户Prancipal的方式:

你会留下ldapProvider:

<beans:bean id="ldapProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">   

....

<beans:bean id="customUserDetailsMapper" class="xxxxx.CustomUserDetailsMapper">
    <beans:constructor-arg ref="customUserDetailService" />
</beans:bean>

<beans:bean id="customUserDetailService" class="xxxxxx.CustomUserDetailService">
</beans:bean>

定义自定义UserDatailsMapper:

public class CustomUserDetailsMapper extends LdapUserDetailsMapper {

private UserDetailsService userDetailService;

public CustomUserDetailsMapper (UserDetailsService userDetailService) {
    this.userDetailService = userDetailService;
}

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx,
        String username, Collection<? extends GrantedAuthority> authorities) {

    return (UserDetails) this.userDetailService.loadUserByUsername(username);
}

}

并定义Custom UserDetailsS​​ervice:

public class CustomUserDetailService implements UserDetailsService {


@Autowired
protected UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDb user = userRepository.findByUserName(username);

    if (UserDb  == null) {
        throw new UsernameNotFoundException(username);
    }           

    // Construct customUserDetails

    return (UserDetails)customUserDetails;
}