如果我们需要从ActiveDirectory中获取用户属性(例如名称,sn等),则不能使用Specialized LDAP身份验证提供程序进行配置,该提供程序使用Active Directory配置约定,例如“ springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider” >
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/", "logout").permitAll().and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
}
@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider(domain, url);
adProvider.setConvertSubErrorCodesToExceptions(true);
adProvider.setUseAuthenticationRequestCredentials(true);
return adProvider;
}
,然后使用AuthenticationManager,如下所示。
Authentication auth = new UsernamePasswordAuthenticationToken(userName, password);
Authentication a = authenticationManager.authenticate(auth);
但是,对于正确的用户名和密码,我得到a.isAuthenticated()为true,也为我的用户名得到a.getName()。但是,如何检索sn,dispalyname,name和其他属性。我们是否需要编写一个CustomActiveDirectoryLdapAuthenticationProvider,如此处所述 http://code-addict.pl/active-directory-spring-security/
答案 0 :(得分:2)
您没有。 Spring Security带有一个this界面
/**
* Creates a fully populated UserDetails object for use by the security framework.
*
* @param ctx the context object which contains the user information.
* @param username the user's supplied login name.
* @param authorities
* @return the user object.
*/
UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities);
当前仅映射搜索返回的组。
// Map the roles
for (int i = 0; (this.roleAttributes != null)
&& (i < this.roleAttributes.length); i++) {
String[] rolesForAttribute = ctx.getStringAttributes(this.roleAttributes[i]);
if (rolesForAttribute == null) {
this.logger.debug("Couldn't read role attribute '"
+ this.roleAttributes[i] + "' for user " + dn);
continue;
}
for (String role : rolesForAttribute) {
GrantedAuthority authority = createAuthority(role);
if (authority != null) {
essence.addAuthority(authority);
}
}
}
但是,实现自己的 UserDetailsMapper 可以检索从LDAP返回的所有记录。
您只需确定要获取的属性
Object attribute = ctx.getObjectAttribute("some-ldap-attribute");
这是在身份验证事件期间获取自定义值的方式。
如果您只想查询和搜索LDAP目录中的数据,则可以利用LdapUserDetailsMapper
它旨在模仿 RestTemplate 对于HTTP(对于LDAP)的作用。