java ldap登录

import static javax.naming.Context.INITIAL_CONTEXT_FACTORY;
import static javax.naming.Context.PROVIDER_URL;
import static javax.naming.Context.SECURITY_AUTHENTICATION;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;

import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.shiro.codec.Base64;
import org.springframework.stereotype.Component;

import com.jiuqi.bi.util.StringUtils;

@Component
public class LdapLogin implements EIPLogin{
    /**
     * ldap链接地址
     */
    private static final String LDAP_URL = "ldap://x.x.x.x:389";
    
    /**
     * 密码后缀
     */
    private static final String PASSWORD_SUF = "";
    
    /**
     * 链接ldap的环境变量
     */
    private static final Hashtable<String, String> ENVIRONMENT = new Hashtable<>();
    
    static {
        //初始化不需要改变的信息
        ENVIRONMENT.put(INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        ENVIRONMENT.put(SECURITY_AUTHENTICATION, "simple");
        ENVIRONMENT.put(PROVIDER_URL, LDAP_URL);
    }
    @Override
    public boolean login(String username, String password) {
        //验证参数
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return false;
        }
        //解密
        username = decodeStr(username);
        password = decodeStr(password);
        //密码设置密码后缀
        ENVIRONMENT.put(SECURITY_PRINCIPAL, username+PASSWORD_SUF);
        ENVIRONMENT.put(SECURITY_CREDENTIALS, password);
        DirContext context = null;
        try {
            context = new InitialDirContext(ENVIRONMENT);
        } catch (NamingException e) {
            return false;
        } finally {
            if (context != null){
                try {
                    context.close();
                } catch (NamingException e) {
                    return false;
                }
            }
        }
        return context != null;
    }
    
    /**
     * 解密字符串
     * @param str
     * @return
     */
    private String decodeStr(String str) {
        if(StringUtils.isEmpty(str)) {
            return "";
        }
        return Base64.decodeToString(Base64.decodeToString(str));
    }
}

不多解释了,自己看代码吧,复制改改就可以使用

posted @ 2021-06-16 13:47  随意的马蒂洛克  阅读(357)  评论(0编辑  收藏  举报