使用Spring Security 4进行自定义LDAP身份验证

时间:2015-02-17 05:00:14

标签: java spring spring-security ldap spring-ldap

在我的非Spring Security应用程序中,我们使用LDAP通过使用他的ID和密码连接到LDAP服务器来验证用户。如果连接成功,则对用户进行身份验证,并从LDAP获取其详细信息。以下是代码:

private void getLdapConnection(UserSignInObject userSignInObject) {
    LdapContextSource ctxSrc = new LdapContextSource();
    ctxSrc.setUrl("ldap://mjkoldc-03.red.com");
    ctxSrc.setUserDn("mj\\" + userSignInObject.getEmail());
    ctxSrc.setPassword(userSignInObject.getPassword());
    ctxSrc.setReferral("follow");
    ctxSrc.afterPropertiesSet();    
    LdapTemplate tmpl = new LdapTemplate(ctxSrc);
    setLdapTemplate(tmpl);
}

@Override
public DefaultUserObject selectUserDetailsFromLdap(
        UserSignInObject userSignInObject) throws Exception {
    DefaultUserObject user = new DefaultUserObject();
    try {
        getLdapConnection(userSignInObject);
        LdapQuery query = query().base("dc=metaljunction,dc=com")
            .attributes("GivenName", "sn", "mail", "MobilePhone")
            .where("ObjectClass").is("user").and("SamAccountName")
            .is(userSignInObject.getEmail());
        user = ldapTemplate.searchForObject(query,
            new ContextMapper<DefaultUserObject>() {
            @Override
            public DefaultUserObject mapFromContext(Object ctx)
                throws NamingException {
                DirContextAdapter context = (DirContextAdapter) ctx;
                DefaultUserObject user = new DefaultUserObject();
                user.setFirstName(context
                    .getStringAttribute("GivenName"));
                user.setLastName(context.getStringAttribute("sn"));
                user.setEmail(context.getStringAttribute("mail"));
                user.setPhone(context
                    .getStringAttribute("MobilePhone"));
                return user;
            }
            });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return user;
}

要求是在Spring Security 4中实现相同的逻辑。我想在AuthenticationUserDetails对象中保存详细信息。我该怎么做?我正在使用基于Java的配置。这是验证用户身份的唯一方法。

1 个答案:

答案 0 :(得分:0)

您需要实现自己的AuthenticationProvider(即实现org.springframework.security.authentication.AuthenticationProvider的类)并配置Spring Security以使用它。 看看这个:Implement custom AuthenticationProvider in Spring Security 2.06