是否可以使用Spring Security(3.1.X)获取经过身份验证的用户的LDAP信息?

Bil*_*ill 6 ldap spring-security

我使用Spring Security根据Active Directory服务器对用户进行身份验证.CustomUserContext也会注入ldapAuthenticationProvider bean,以提供对其他LDAP属性的访问.一切都很好.我没有问题从认证用户那里拉出我想要的东西.

我遇到的问题是我想要从登录用户以外的用户的Active Directory服务器中检索一些属性,特别是电子邮件地址.是否可以通过利用我已有的功能来实现这一点,或者我唯一的选择是使用完全独立的方法来访问来自不同用户的LDAP属性?

[编辑] 配置如下

安全-config.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sec="http://www.springframework.org/schema/security"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
    <property name="url" value="ldap://xxxx.xxxx.xxx:389" />
    <property name="base" value="dc=corp,dc=global,dc=xxxxx,dc=com" />
    <property name="userDn" value="CN=lna.authquery,OU=LDAPGroups,OU=NorthAmerica,DC=corp,DC=global,DC=xxxxx,DC=com" />
    <property name="password" value="xxxxxxx" />
    <property name="pooled" value="true" />
    <!-- AD Specific Setting for avoiding the partial exception error -->
    <property name="referral" value="follow" />
</bean>

<bean id="ldapAuthenticationProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider" >
    <constructor-arg>
        <bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
            <constructor-arg ref="contextSource" />
            <property name="userSearch">
                <bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
                    <constructor-arg index="0" value="" />
                    <constructor-arg index="1" value="(sAMAccountName={0})" />
                    <constructor-arg index="2" ref="contextSource" />
                </bean>
            </property>
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
            <constructor-arg ref="contextSource" />
            <constructor-arg value="" />
            <property name="groupSearchFilter" value="(member={0})" />
            <property name="searchSubtree" value="true" />
            <!-- Settings below convert the adds the prefix ROLE_ to roles returned from AD -->
        </bean>
    </constructor-arg>
    <property name="userDetailsContextMapper">
       <bean class="net.xxxx.xxxxx.utilities.CustomUserDetailsContextMapper" />
    </property>
</bean>

<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
    <constructor-arg>
        <list>
            <ref local="ldapAuthenticationProvider" />
        </list>
    </constructor-arg>
</bean>

<sec:http pattern="/css/**" security="none"/>
<sec:http pattern="/images/**" security="none"/>
<sec:http auto-config="true" authentication-manager-ref="authenticationManager" >
    <sec:intercept-url pattern="/login.jsp*" requires-channel="https" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <sec:intercept-url pattern="/**" requires-channel="https" access="IS_AUTHENTICATED_FULLY"/>
    <sec:form-login login-page='/login.jsp' 
                    default-target-url="/home.html" 
                    authentication-failure-url="/login.jsp" />
</sec:http>  
Run Code Online (Sandbox Code Playgroud)

CustomeUserDetails.java

package net.xxxx.xxxx.utilities;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

public class CustomUserDetails extends User {

    private static final long serialVersionUID = 1416132138315457558L;

     // extra instance variables
       final String fullname;
       final String email;
       final String title;

       public CustomUserDetails(String username, String password, boolean enabled, boolean accountNonExpired,
             boolean credentialsNonExpired, boolean accountNonLocked,
             Collection<? extends GrantedAuthority> authorities, String fullname,
             String email, String title) {

           super(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities);

           this.fullname = fullname;
           this.email = email;
           this.title = title;
       }

       public String getFullname() {
           return this.fullname;
       }

       public String getEmail() {
           return this.email;
       }

       public String getTitle() {
           return this.title;
       }
}
Run Code Online (Sandbox Code Playgroud)

CustomUserDetailsContextMapper.java

package net.xxxx.xxxxx.utilities;

import java.util.Collection;

public class CustomUserDetailsContextMapper implements UserDetailsContextMapper {

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

        String fullname = "";
        String email = "";
        String title = "";

        Attributes attributes = ctx.getAttributes();
        try {
            fullname = (String) attributes.get("displayName").get(); 
            email = (String) attributes.get("mail").get(); 
            title = (String) attributes.get("title").get(); 
        } catch (NamingException e) {
            e.printStackTrace();
        }

        CustomUserDetails details = new CustomUserDetails(username, "", true, true, true, true, authorities, fullname, email, title);
        return details;
    }

    public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {

    }

}
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 7

我终于找到了如何做到这一点.我正在回答这个问题,以防其他人需要这样做.如果我是唯一一个,我会感到惊讶.

首先,我必须将我的security-config.xml文件移出WEB-INF结构并将其放在spring资源目录下.contextSource我能够重用的bean.但是CustomUserDetailsContextMapper.java,CustomUserDetails.java由于它们太过于特定于Spring安全性而不是仅仅从未经身份验证的用户检索LDAP数据,因此我无法重用该类或类.

我最后为LDAP访问编写了一个单独的类,该类具有公共contextSource自动装配的功能.该类如下所示.

LdapDao.java

package net.xxxxx.xxx.dao;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.naming.directory.Attributes;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.stereotype.Component;

@Component
public class LdapDao {

    LdapTemplate template;

    @Autowired
    public LdapDao(LdapContextSource contextSource) {
        template = new LdapTemplate(contextSource);
    }

    @SuppressWarnings("unchecked")
    public Map<String, String> getUserAttributes(String username) {
        Map<String, String> results = new HashMap<String, String>();

        String objectClass = "samAccountName=" + username;
        LinkedList<Map<String, String>> list = (LinkedList<Map<String, String>>) template.search("", objectClass, new UserAttributesMapper());
        if (!list.isEmpty()) {
            // Should only return one item
            results = list.get(0);
        }
        return results;
    }

    private class UserAttributesMapper implements AttributesMapper {

        @Override
        public Map<String, String> mapFromAttributes(Attributes attributes) throws javax.naming.NamingException {
            Map<String, String> map = new HashMap<String, String>();

            String fullname = (String) attributes.get("displayName").get(); 
            String email = (String) attributes.get("mail").get(); 
            String title = (String) attributes.get("title").get();

            map.put("fullname", fullname);
            map.put("email", email);
            map.put("title", title);
            return map;
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)


Bre*_*yan 4

@Bill 你所做的很棒,尽管实际上有一种更简单的方法。无需求助于LdapTemplate,只需使用您已经注册的 BeanDefaultLdapAuthoritiesPopulatorFilterBasedLdapUserSearch。通过这种方式,您可以获得相同的UserDetails对象,该对象也填充了权限,并为您的net.xxxx.xxxxx.utilities.CustomUserDetailsContextMapper.

您需要执行以下操作:

  1. 拆分出需要注入为命名 bean 的 bes,并使用refproperty 和constructor-args ( DefaultLdapAuthoritiesPopulator, FilterBasedLdapUserSearch, net.xxxx.xxxxx.utilities.CustomUserDetailsContextMapper) 的属性。
  2. 在您的LdapDao注入引用中:
    • FilterBasedLdapUserSearch-userSearch
    • DefaultLdapAuthoritiesPopulator-authPop
    • net.xxxx.xxxxx.utilities.CustomUserDetailsContextMapper-userMapper
  3. 将以下方法添加到您的LdapDao

public UserDetails getUserDetails(final String username) {
    try {
        DirContextOperations ctx = userSearch.searchForUser(username);
        return userMapper.mapUserFromContext(ctx, username,
                authPop.getGrantedAuthorities(ctx, username));
    } catch (UsernameNotFoundException ex) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您只需调用即可getUserDetails(String)获取与检索当前登录上下文时相同的对象,并且可以使用相同的代码等。