Active Directory使用spring安全性



我的要求是。我有一个登录页面,其中有春季安全。首先,我想用活动目录验证用户名和密码,如果用户存在,那么我需要检查数据库中的用户名。

我已经尝试在线使用spring安全进行LDAP身份验证。但是我不知道怎么才能做到这一点。

您需要做的是注入LdapAuthenticator的自定义实现。我做过类似的事情,但在一个老项目,因为3年你可能不得不改变代码。基本上我们是这样做的(仔细阅读评论):

import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.LdapAuthenticator;

public class LdapAuthenticatorImpl implements LdapAuthenticator {
    private DefaultSpringSecurityContextSource contextFactory;
    private String principalPrefix = "";
    public DirContextOperations authenticate(Authentication authentication) {
            // Grab the username and password out of the authentication object.
            String principal = principalPrefix + authentication.getName();
            String password = "";
            if (authentication.getCredentials() != null) {
                    password = authentication.getCredentials().toString();
            }
            // If we have a valid username and password, try to authenticate.
            if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
                    InitialLdapContext ldapContext = (InitialLdapContext) contextFactory.getReadWriteContext();
                    //We attempt the super class authentication which will validate the credentials. In case 
                    //of success it will return an instance of authAdapter otherwise it will throw BadCredentialsException.
                    DirContextOperations authAdapter = super.authenticate(authentication) ;
                    //We can consider authentication successful with LDAP.
                    //TODO check the user in the database

                    //
                    return authAdapter;
            } else {
                    throw new BadCredentialsException("Blank username and/or password!");
            }
    }
}

在配置文件中,您需要用您的实现覆盖名为ldapAuthenticator的现有bean。下面的示例使用grails语法,但您可以在application-descriptor.xml中执行相同的操作:

    ldapAuthenticator(CustomBindAuthenticator, ref('contextSource')) {
        userSearch = ref('ldapUserSearch')
    } 

也可以在XML中这样配置:

<bean id="ldapAuthenticator" class="com.mypackage.myClass">
      <constructor-arg ref="contextSource"/>
      <property name="userSearch" ref="ldapUserSearch"/>
   </bean>

最新更新