Java连LDAP

该代码片段展示了如何使用Java的JNDI和LDAP接口进行用户身份验证。首先,它设置LDAP连接参数,然后通过提供的用户名和密码尝试建立连接。接着,它执行一个搜索操作来获取用户的相关信息,如邮件、sAMAccountName等。如果找到用户,它会进一步验证提供的密码是否与从LDAP检索到的dcName匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import javax.annotation.Resource;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import java.util.Properties;

Object principal = token.getPrincipal();//输入的用户名
Object credentials = token.getCredentials();//输入的密码
String userName = principal.toString();
String password = new String((char[]) credentials);

DirContext ctx = null;
String rootDN = "DC=xx,DC=cn";
String rootName = "CN=UatEnv,OU=Test account,DC=xx,DC=cn";   // 账号
String rootPassword = "RootPassword";    // 密码
String ldapURL = "ldap://ldap.xx.cn:389"; 
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
env.put(Context.SECURITY_PRINCIPAL, rootName);
env.put(Context.SECURITY_CREDENTIALS, rootPassword);
env.put(Context.PROVIDER_URL, ldapURL);
//  **解决 乱码 的关键一句
env.put("java.naming.ldap.attributes.binary", "objectGUID");

try {
    //  建立连接
    ctx = new InitialLdapContext(env, null);
    log.info("[{}-1] ctx:{}", this.getClass().getName(), ctx.toString());
} catch (Exception e) {
    log.error("[{}-1]:{}", this.getClass().getName(), e.getMessage());
    if (ctx != null) {
        ctx.close();
    }
    throw new UnknownAccountException();
}

//  定义要取出的属性
String atts[] = {
        "mail",
        "sAMAccountName",
        "uid",
        "OU",
        "title",
        "badpwdcount",
        "name",
        "distinguishedName"
};
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(atts);

//  定义条件
String rootFilter = String.format("(sAMAccountName=%s)", userName);
//  查询用户名对应信息
NamingEnumeration<SearchResult> results = ctx.search(rootDN, rootFilter, searchCtls);

log.info("[{}] SearchResult:{}", this.getClass().getName(), results.toString());

if (results == null || !results.hasMore()) {
    throw new UnknownAccountException();
} else {
    if (results.hasMore()) {
        SearchResult sr = results.next();
        log.info("[{}] SearchResultAttributes====================================", this.getClass().getName());
        NamingEnumeration namingEnumeration = sr.getAttributes().getAll();
        while (namingEnumeration.hasMore()) {
            log.info(namingEnumeration.next().toString());
        }
        userName = sr.getAttributes().get("sAMAccountName").get().toString();
        String dcName = sr.getAttributes().get("distinguishedName").get().toString();
        String email = sr.getAttributes().get("mail").get().toString();
        String title = sr.getAttributes().get("title").get().toString();
        log.info("user:{},email:{},title:{},dcName:{}", userName, email, title, dcName);
        log.info("[{}] SearchResultAttributes====================================", this.getClass().getName());

        //  验证用户名密码是否匹配
        env.put(Context.SECURITY_PRINCIPAL, dcName);
        env.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(env);
            log.info("[{}-2] ctx:{}", this.getClass().getName(), ctx.toString());            
        } catch (Exception e) {
            log.error("[{}-2]:{}", this.getClass().getName(), e.getMessage());
            throw new IncorrectCredentialsException();
        } finally {
            ctx.close();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值