LdapAuthUtil.java 1.66 KB
package com.ui.ldaputil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Component;

import javax.naming.directory.SearchControls;
import java.util.List;

/**
 * Created by jimi on 2017/12/26.
 */
@Component
public class LdapAuthUtil {

    private static final Logger logger= LoggerFactory.getLogger(LdapAuthUtil.class);

    @Autowired
    LdapTemplate ldapTemplate;

    public boolean login(String userName, String passWord){
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "person"))
                .and(new EqualsFilter("sAMAccountName", userName));
        String[] urls = ((YhLdapContextSource) ldapTemplate.getContextSource()).getUrls();
        logger.info("ldap  urls :{}",urls);
        return ldapTemplate.authenticate("", filter.toString(), passWord);
    }

    public LdapUser getUser(String userName){
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "person"))
                .and(new EqualsFilter("sAMAccountName", userName));
        LdapUser user = null;
        int SearchScope = SearchControls.SUBTREE_SCOPE;
        AttributesMapper<LdapUser> attr = new LdapMapUser();
        List<LdapUser> users=ldapTemplate.search("",filter.toString(), SearchScope, attr);
        if (users.size() !=0){
            user=users.get(0);
        }
        return user;
    }
}