具有Active Directory和数据库角色的Spring Security

时间:2014-12-19 14:31:22

标签: spring spring-security active-directory

我正在尝试将Spring Security与Active Directory用户名和密码一起使用。另外,我有一个数据库Roles表,它与包含Active Directory用户名的User表有关系(User表与Active Directory无关,它完全独立我只是把用户名放在那个表中所以我可以与角色匹配)

我正在关注这个例子 http://krams915.blogspot.com/2012/01/spring-security-31-implement_1244.html

问题是我无法在CustomUserDetailsS​​ervice类的loadUserByUsername方法中看到密码的使用位置。

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            org.krams.domain.User domainUser = userRepository.findByUsername(username);

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;

            return new User(
                    domainUser.getUsername(), 
                    domainUser.getPassword().toLowerCase(),
                    enabled,
                    accountNonExpired,
                    credentialsNonExpired,
                    accountNonLocked,
                    getAuthorities(domainUser.getRole().getRole()));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

根据我的理解,此行会针对数据库userRepository.findByUsername(username);

验证用户名

但是如何在那里使用lpad验证呢?我可以使用像http://www.javaxt.com/Tutorials/Windows/How_to_Authenticate_Users_with_Active_Directory

这样的身份验证实现

更新

我正在尝试使用CustomUserDetailsContextMapper

XML

<authentication-manager >
    <authentication-provider ref="ldapActiveDirectoryAuthProvider" />
</authentication-manager>

<beans:bean id="ldapActiveDirectoryAuthProvider" 
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <beans:constructor-arg value="domain" />
    <beans:constructor-arg value="ldap://NAME/"/> 
    <beans:property name="userDetailsContextMapper" ref="tdrUserDetailsContextMapper"/>
    <beans:property name="useAuthenticationRequestCredentials" value="true"/>
</beans:bean>

<beans:bean id="tdrUserDetailsContextMapper" class="com.test8.security8.service.CustomUserDetailsContextMapper"/>

自定义类

public class CustomUserDetailsContextMapper implements UserDetailsContextMapper, Serializable{

    private static final long serialVersionUID = 3962976258168853984L;

    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authority) {
        String role="admin";
        System.out.println("TEST");
        if(username.equals("usuario"))role="admin";
        else role="user";
        List authList = getAuthorities(role);

        return new User(username, "", true, true, true, true, authList);
    }

    private List getAuthorities(String role) {

        List authList = new ArrayList();
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));

        //you can also add different roles here
        //for example, the user is also an admin of the site, then you can add ROLE_ADMIN
        //so that he can view pages that are ROLE_ADMIN specific
        if (role != null && role.trim().length() > 0) {
            if (role.equals("admin")) {
                authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
        }

        return authList;
    }

    @Override
    public void mapUserToContext(UserDetails arg0, DirContextAdapter arg1) {
        // TODO Auto-generated method stub      
    }
}

我想我差不多了,我没有收到错误,但它似乎无法映射任何用户,System.out.println("TEST");行永远不会执行。它可能是与URL /域相关的东西吗?我确定URL是正确的,因为如果我更改它,我会收到错误。

1 个答案:

答案 0 :(得分:0)

我最终使用了M.Deinum建议的UserDetailsContextMapper。我还创建了风俗SpringSecurityLdapTemplate和ActiveDirectoryLdapAuthenticationProvider。

在我的自定义ActiveDirectoryLdapAuthenticationProvider中,我更改了以下方法:

private LdapContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String,String> env = new Hashtable<String,String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.REFERRAL, "follow");

    try {
        return new InitialLdapContext(env, null);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials();
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
} 

这对我来说很重要: env.put(Context.REFERRAL,“follow”);

在SpringSecurityLdapTemplate自定义类

public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
        String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls));

   filter, searchControls);
    if (logger.isDebugEnabled()) {
        logger.debug("Searching for entry under DN '" + ctxBaseDn
                + "', base = '" + searchBaseDn + "', filter = '" + filter + "'");
    }

    Set<DirContextOperations> results = new HashSet<DirContextOperations>();
    try {

        while (resultsEnum.hasMore()) {


            SearchResult searchResult = resultsEnum.next();

            DirContextAdapter dca = new DirContextAdapter();

            //dca=(DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");

            if (logger.isDebugEnabled()) {
                logger.debug("Found DN: " + dca.getDn());
            }
            results.add(dca);
        }
    } catch (PartialResultException e) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.info("Ignoring PartialResultException");
    }

    if (results.size() == 0) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }

    if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }

    return results.iterator().next();
}

这对我有用,但这是一个非常特殊的场景。感谢M. Deinum指出我正确的方向。