首页 > 解决方案 > 如何使用 Spring Security 从 LDAP 获取用户角色

问题描述

我能够与 ldap 连接并获得响应,但是在我的 Principal 对象权限中,我猜想其中角色详细信息可用的大小为零。为了获取 ldap 角色详细信息,我需要传递哪些额外的输入?

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.ldapAuthentication()
        .userDnPatterns("uid={0},ou=TestOu")
        .contextSource()
        .url("ldaps://XX:768");
        }

我也尝试使用 DirContextOperations 对象,它包含除角色之外的许多属性,角色在 ldapit 中定义,我能够在运行 ldap 查询时获取角色,问题仅通过 spring security

请帮忙

标签: spring-security-ldap

解决方案


知道了 !!!!!实现一个自定义的 AuthenticationProvider 和 LdapAuthenticator,它使用了 BindAuthenticator。我们必须使用 BindAuthenticator 设置以下内容

     authenticator.setUserDnPatterns(new String[]{"XX"});
     authenticator.setUserAttributes(new String[]{"nsrole"});

在配置中

@Override public void configure(AuthenticationManagerBuilder auth) 抛出异常 {

    auth.authenticationProvider(this.customLdapAuthenticationProvider());
}

@Bean(name = "ldapAuthenticationProvider")
public AuthenticationProvider customLdapAuthenticationProvider() {

    LdapUserDetailsMapper userDetailsMapper = new UserMapper();

    CustomLdapAuthenticationProvider provider = new CustomLdapAuthenticationProvider(this.ldapAuthenticator(),
            new NullLdapAuthoritiesPopulator());
    provider.setUserDetailsContextMapper(userDetailsMapper);

    return provider;

}

@Bean(name = "ldapAuthenticator")
public LdapAuthenticator ldapAuthenticator() {

    BindAuthenticator authenticator = new BindAuthenticator(this.contextSource());
    authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
    authenticator.setUserAttributes(new String[] { "nsrole" });
    return authenticator;
}

@Bean(name = "contextSource")
public DefaultSpringSecurityContextSource contextSource() {

    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(ldapUrl);
    return contextSource;
}

私有类 UserMapper 扩展 LdapUserDetailsMapper {

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


        List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();

        Attributes attrs = ctx.getAttributes();

            Sysout(attr)
        UserDetails userDetails = super.mapUserFromContext(ctx, username, roles);

        return userDetails;
    }

}


推荐阅读