如何使用InetOrgPersonContextMapper类

时间:2017-06-09 03:08:58

标签: spring spring-security spring-ldap

我已通过Spring Security验证并授权Active Directory。 但无法检索LDAP属性,例如MAIL。 我尝试使用InetOrgPersonContextMapper ...

@Bean
public InetOrgPersonContextMapper inetOrgPersonContextMapper(){
    InetOrgPersonContextMapper contextMapper = new InetOrgPersonContextMapper();
    return contextMapper;
}
 @Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
    ldapAuthenticationProvider.setUserDetailsContextMapper(inetOrgPersonContextMapper());
    return ldapAuthenticationProvider;
}

但是当我在控制器中尝试retrive属性时,我得到了ClassCastExeption

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    InetOrgPerson person = (InetOrgPerson)auth.getPrincipal();

请告诉我reitrive属性的正确方法。

1 个答案:

答案 0 :(得分:0)

我想这不是更好的方法,但它正在发挥作用。 如果有人知道如何做得更好,请告诉我。

@Bean
public UserDetailsContextMapper userDetailsContextMapper(){
    return new LdapUserDetailsMapper(){
        @Override
        public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
            InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
            UserDetails cm = personContextMapper.mapUserFromContext(ctx,username,authorities);
            String MAIL = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getMail();
            String FullName = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getDisplayName();
            System.out.println("MAIL: " + MAIL + " Full Name: " + FullName);
            return cm;
        }
    };
}