spring-security-ldap - 如何使用 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
请帮忙
解决方案
知道了 !!!!!实现一个自定义的 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;
}
}
推荐阅读
- vue.js - 如何在 Vue2Leaflet 中使用 Leaflet Fullscreen
- typescript - 打字稿使只读属性可写
- java - Java 10 上带有 Oracle 时间戳的超前时钟
- macos - Safari 使用什么 API 来获取帐户密码
- python - 带有 numpy 的 PySpark:性能不稳定
- android - 为什么我的应用程序运行两次?
- vba - 列范围的最大值
- ios - 如何使用 Siri 快捷方式在我的应用程序中显示特定页面?
- javascript - 多个页面的 React-Redux 状态形状
- javascript - 如何从数组(例如本地图像或网站)添加到滑块图像?