java jndi ldap,使用JNDI进行LDAP身份验证

I'd like to test if a given user and password of a LDAP user are correct.

I sorted out that jndi is the library to use.

I found this simple class:

package myldap;

import java.util.Hashtable;

import javax.naming.AuthenticationException;

import javax.naming.Context;

import javax.naming.NamingEnumeration;

import javax.naming.NamingException;

import javax.naming.directory.Attributes;

import javax.naming.directory.DirContext;

import javax.naming.directory.InitialDirContext;

import javax.naming.directory.SearchControls;

import javax.naming.directory.SearchResult;

// boolean function to test user and pwd

public static boolean userVerify(String user, String password){

boolean userVerify = false;

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

env.put(Context.PROVIDER_URL, "ldap://192.168.48.10");

env.put(Context.SECURITY_AUTHENTICATION, "simple");

env.put(Context.SECURITY_PRINCIPAL, "CN=" + user + ",conn");

env.put(Context.SECURITY_CREDENTIALS, password);

try {

DirContext authContext = new InitialDirContext(env);

userVerify = true;

authContext.close();

} catch (AuthenticationException authEx) {

//("Authentication Exception!");

userVerify = false;

} catch (NamingException namEx) {

//("Something went wrong!");

userVerify = false;

}

return userVerify;

}

since i am trying to make it work i am playing around with the parameters.

The values i put in the function are

INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

PROVIDER_URL, "ldap://192.168.48.10");

SECURITY_AUTHENTICATION, "simple");

SECURITY_PRINCIPAL, "CN=" + user + ",conn");

SECURITY_CREDENTIALS, password);

with the above i get AuthenticationException, that is the best result i could achieve, by changing things I obtain NamingException, so it seems i am less close to the solution.

In particular i am not sure about SECURITY_PRINCIPAL.

Does anyone have experience and can give advice on how to pass those values correctly pinpointing which ones are wrong? Of course I would like to connect and not raise exceptions.

解决方案

The SECURITY_PRINCIPAL needs to be the entire DN of the user you are authenticating as.

Usually you have to do a prior search of the DIT to find that, using some unique attribute of the user such as his email address, and usually you have to authenticate as some other administrative user built into the DIT that has the rights to do that search. Then, when you've found the DN, you change the SECURITY_PRINCIPAL and do a reconnect.

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值