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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值