All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.starxmind.boot.ldap.LdapClient Maven / Gradle / Ivy

package com.starxmind.boot.ldap;

import com.starxmind.bass.sugar.Asserts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;

import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Ldap操作模板
 *
 * @author pizzalord
 * @since 1.0
 */
@Slf4j
public class LdapClient {
    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * 获取用户信息
     *
     * @return
     */
    public LdapUser queryUserByUid(String uid) {
        //过滤条件
//        String filter = "(&(objectClass=*)(uid=*))";
//        String filter = "(|(uid=" + uid + "))";
        String filter = "(uid=" + uid + ")";
        List ldapUsers = searchUsersByFilter(filter);
        if (CollectionUtils.isEmpty(ldapUsers)) {
            return null;
        }
        return ldapUsers.get(0);
    }

    public List queryAllUsers() {
        String filter = "(&(objectClass=*)(uid=*))";
        return searchUsersByFilter(filter);
    }

    public List searchUsersByFilter(String filter) {
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List search = ldapTemplate.search("", filter, controls, (ContextMapper) o -> {
            DirContextOperations ctx = (DirContextOperations) o;

            byte[] userPassword = (byte[]) ctx.getObjectAttribute("userPassword");
            String userPasswordDecoded = new String(userPassword);

            return LdapUser.builder()
                    .cn(ctx.getStringAttribute("cn"))
                    .sn(ctx.getStringAttribute("sn"))
                    .uid(ctx.getStringAttribute("uid"))
                    .userPassword(userPasswordDecoded)
                    .displayName(ctx.getStringAttribute("displayName"))
                    .mail(ctx.getStringAttribute("mail"))
                    .description(ctx.getStringAttribute("description"))
                    .uid(ctx.getStringAttribute("uid"))
                    .build();
        });

        return search;
    }

    public void authenticate(String uid, String password) throws NamingException, NoSuchAlgorithmException {
        LdapUser ldapUser = queryUserByUid(uid);
        Asserts.notNull(ldapUser, "无此用户");
        SHA1Utils.verifyPassword(ldapUser.getUserPassword(), password);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy