Java使用LDAP协议验证用户登录的问题

xharry 2008-06-29 11:15:43
有用过Java登录LDAP服务器,并验证用户名和密码的,给个例子。我看过了Novel的JLDAP,一个是不方便下,而是不知道哪个例子是可以用的。

有人用过用java做过类似的登录代码吗?

...全文
5805 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Sou2012 2008-07-07
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 xharry 的回复:]
谢谢各位,最后我用了Mozilla的LDAPSDK包,代码如下,如果你需要,请参考以下:


Java code
package org.charry.lib.ldap;

import netscape.ldap.*;
import netscape.ldap.util.*;
import java.util.*;
import javax.naming.directory.Attribute;

public class LDAPUtil {
private static UserProfile verifyLogin(String user, String pwd) {
String LDAPDN = "DC=charry,DC=org";
Strin…
[/Quote]

谢谢楼主提供
xharry 2008-07-06
  • 打赏
  • 举报
回复
谢谢各位,最后我用了Mozilla的LDAPSDK包,代码如下,如果你需要,请参考以下:


package org.charry.lib.ldap;

import netscape.ldap.*;
import netscape.ldap.util.*;
import java.util.*;
import javax.naming.directory.Attribute;

public class LDAPUtil {
private static UserProfile verifyLogin(String user, String pwd) {
String LDAPDN = "DC=charry,DC=org";
String MY_FILTER = "sAMAccountName=" + user;
String MY_ATTR[] = { "sn", "buildingName", "businessCategory", "c",
"co", "departmentNumber", "description", "displayName",
"distinguishedName", "employeeType", "givenName",
"homeDirectory", "info", "l", "mail", "manager", "mobile",
"name", "physicalDeliveryOfficeName", "postalAddress",
"streetAddress", "telephoneNumber", "textEncodedORAddress",
"title", "department", "division", "employeeID", "location",
"mailNickName", "sAMAccountName", "wWWHomePage" };

LDAPConnection ld = new LDAPConnection();
String LDAPServersStr = "ssuzdc3.charry.org;ssuzdc4.charry.org";
String[] LDAPServers = LDAPServersStr.split(";");
String LDAPServer = "";
for (int i = 0; i < LDAPServers.length; i++) {
LDAPServer = LDAPServers[i];
try {
ld.connect(LDAPServer, LDAPv2.DEFAULT_PORT);
ld.authenticate(user + "@charry.org", pwd);
break;
} catch (LDAPException e) {
e.printStackTrace();
}
}

try {
LDAPSearchResults res = ld.search(LDAPDN, LDAPConnection.SCOPE_SUB,
MY_FILTER, MY_ATTR, false);
LDAPEntry findEntry = res.next();

String value = "";
LDAPAttribute attribute = null;
Enumeration enumVal = null;

attribute = findEntry.getAttribute("mail");
if (attribute != null) {
enumVal = attribute.getStringValues();
value = (String) enumVal.nextElement();
System.out.println(value);
}


} catch (Exception e) {
e.printStackTrace();
}
}
}

Sou2012 2008-07-01
  • 打赏
  • 举报
回复
这篇文件也许对你有帮助

http://blog.t-times.net/ada/comments/Computer/Java/2005-02-21/1
Sou2012 2008-07-01
  • 打赏
  • 举报
回复
一共两个java类,加一个配置文件

LDAP.java---------------连接LDAP服务器,判断用户名密码正确与否

UMParas.java----------jDom解析xml配置文件

ldapconfig.xml---------配置文件,里面有服务器的参数信息

LDAP.java 代码
package ldap2;

import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;

public class LDAP {

private Hashtable env = null;

private DirContext ctx = null;

private boolean islogin = false;

StringBuffer url;

String host;

String port;

String admin;

String password;

String baseDN;

public LDAP(String id, String pwd) {
try {
host = UMParas.getPara("hostname");
port = UMParas.getPara("port");
baseDN = UMParas.getPara("basedn");
admin = UMParas.getPara("admin");
password = UMParas.getPara("pwd");
url = new StringBuffer("LDAP://");
url.append(host).append(":").append(port);
url.append("/").append(baseDN);

} catch (Exception e) {
e.printStackTrace();
System.out.println("");
}
// pwd="secret";
env = new Hashtable();

env.put("java.naming.factory.initial",
"com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.provider.url", url.toString());
env.put(Context.SECURITY_AUTHENTICATION, "simple");

env.put("java.naming.security.principal", admin);
env.put("java.naming.security.credentials", password);
System.out.println("-------------");
}

public boolean checkAd() { //admin用户验证
try {
System.out.println("-----ddd--------");
InitialContext iCnt = new InitialContext(env);
System.out.println("-------eee------");
islogin = true;
} catch (AuthenticationException aue) {
// aue.printStackTrace();
islogin = false;

} catch (NamingException e) {

e.printStackTrace();
} catch (Exception eee) {
eee.printStackTrace();

} finally {
try {
ctx.close();
} catch (Exception ie) {

}
}
return islogin;
}

public boolean userLogin(String userName, String password) { //新建用户验证。
Hashtable envi = new Hashtable();
try {
envi.put("java.naming.factory.initial",
"com.sun.jndi.ldap.LdapCtxFactory");
envi.put("java.naming.provider.url", url.toString());
envi.put(Context.SECURITY_AUTHENTICATION, "simple");
envi.put("java.naming.security.principal", userName);
envi.put("java.naming.security.credentials", password);
InitialContext iCnt = new InitialContext(envi);
return true;
} catch (Exception e) {
//e.printStackTrace();
return false;
} finally {
try {
ctx.close();
} catch (Exception ie) {

}
}
}
}





UMParas.java 代码
package ldap2;

import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;

public class UMParas {

private static HashMap prop;

private static long lastLoadTime;

private static long interval = 0x186a0L; //refresh per 100 second
// static Class class$0; /* synthetic field */

public UMParas() {
}

//input an para and return the result
public static synchronized String getPara(String paras)
throws IllegalArgumentException {
if (paras == null || paras.trim().length() == 0)
throw new IllegalArgumentException("Parameter's value invalid.");
long currentTime = System.currentTimeMillis();
if (prop == null || currentTime - lastLoadTime > interval)
reloadDom();
Object obj = prop.get(paras);
if (obj != null)
return (String) obj;
else
return null;
}

//load the xml file
private static synchronized void reloadDom() {
if (prop == null)
prop = new HashMap();
SAXBuilder builder = new SAXBuilder();
Document read_doc = null;
try {
read_doc = builder.build(UMParas.class
.getResource("ldapconfig.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element rootElement = read_doc.getRootElement();
List list = rootElement.getChildren("para");
for (Iterator i = list.iterator(); i.hasNext();) {
Element current = (Element) i.next();
List item = current.getChildren("item");
Attribute code;
Attribute value;
for (Iterator j = item.iterator(); j.hasNext(); prop.put(code
.getValue(), value.getValue())) {
Element init = (Element) j.next();
code = init.getAttribute("code");
value = init.getAttribute("value");
}

}
System.out.println("load sucess");
lastLoadTime = System.currentTimeMillis();
}

public static void main(String args[]) {
System.out.println(getPara("hostname"));
}

}



ldapconfig.xml 代码
<?xml version="1.0" encoding="GBK"?>
<sys_para>
<para>
<item code="hostname" value="192.168.1.106" description="LDAP服务器IP"/>
<item code="port" value="10389" description="服务器端口"/>
<item code="admin" value="uid=admin,ou=system" description="管理员帐号"/>
<item code="pwd" value="secret" description="密码"/>
<item code="basedn" value="ou=system" description="组织名(基准DN)"/>
</para>
</sys_para>
xharry 2008-06-30
  • 打赏
  • 举报
回复
请copy这个URL到浏览器地址栏:

http://tu.6.cn/pic/show/id/90968
  • 打赏
  • 举报
回复
看不到图片
xharry 2008-06-30
  • 打赏
  • 举报
回复
图片没有贴上

在这里:http://tu.6.cn/pic/show/id/90968



[img=http://tu.6.cn/pic/show/id/90968]图片[/img]
xharry 2008-06-30
  • 打赏
  • 举报
回复
ilysony可以解释一下嘛?

我按照你的代码,修改如下,可是还是不能登陆,用户名和密码都是对的。

我的信息格式如下:

[img=http://tu.6.cn/pic/show/id/90968]图[/img]

package com.test.ldap;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class UserAuthenticate {
private String URL = "ldap://ssuzdc3:389/";
private String BASEDN = "OU=Local Profile,OU=Users,OU=Suzhou,DC=xxxx,DC=com";
private String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private LdapContext ctx = null;
private Hashtable env = null;
private Control[] connCtls = null;

private void LDAP_connect() {
env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
env.put(Context.PROVIDER_URL, URL + BASEDN);
env.put(Context.SECURITY_AUTHENTICATION, "simple");

try {
ctx = new InitialLdapContext(env, connCtls);
} catch (javax.naming.AuthenticationException e) {
System.out.println("Authentication faild: " + e.toString());
} catch (Exception e) {
System.out.println("Something wrong while authenticating: "
+ e.toString());
}
}

private String getUserDN(String email) {
String userDN = "";

LDAP_connect();

try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en = ctx.search("", "mail=" + email, constraints);
if (en == null) {
System.out.println("No NamingEnumeration.");
}
if (!en.hasMoreElements()) {
System.out.println("No element.");
}
while (en != null && en.hasMoreElements()) {
Object obj = en.nextElement();
if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj;
userDN += si.getName();
userDN += "," + BASEDN;
} else {
System.out.println(obj);
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Exception in search():" + e);
e.printStackTrace();
}

return userDN;
}

public boolean authenricate(String ID, String password) {
boolean valide = false;
String userDN = getUserDN(ID);

try {
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
ctx.reconnect(connCtls);
System.out.println(userDN + " is authenticated");
valide = true;
} catch (AuthenticationException e) {
System.out.println(userDN + " is not authenticated");
System.out.println(e.toString());
valide = false;
} catch (NamingException e) {
System.out.println(userDN + " is not authenticated");
valide = false;
} catch (Exception e) {
e.printStackTrace();
}

return valide;
}

public static void main(String[] args) {
boolean bResult = new UserAuthenticate().authenricate(
"Charry.Wang@xxxx.com", "mypassword");
}
}
老紫竹 2008-06-30
  • 打赏
  • 举报
回复
楼上的收藏一下,虽然没测试过......
老紫竹 2008-06-30
  • 打赏
  • 举报
回复
楼上的收藏一下,虽然没测试过......
Sou2012 2008-06-30
  • 打赏
  • 举报
回复
package com.test.ldap;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;



public class UserAuthenticate {
private String URL = "ldap://localhost:389/";
private String BASEDN = "ou=catalogue,o=test.com";
private String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private LdapContext ctx = null;
private Hashtable env = null;
private Control[] connCtls = null;


private void LDAP_connect(){
env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,FACTORY);
env.put(Context.PROVIDER_URL, URL+BASEDN);//LDAP server
env.put(Context.SECURITY_AUTHENTICATION, "simple");
//此处若不指定用户名和密码,则自动转换为匿名登录

try{
ctx = new InitialLdapContext(env,connCtls);
}catch(javax.naming.AuthenticationException e){
System.out.println("Authentication faild: "+e.toString());
}catch(Exception e){
System.out.println("Something wrong while authenticating: "+e.toString());
}
}


private String getUserDN(String email){
String userDN = "";

LDAP_connect();

try{
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en = ctx.search("", "mail="+email, constraints); //The UID you are going to query,* means all nodes
if(en == null){
System.out.println("Have no NamingEnumeration.");
}
if(!en.hasMoreElements()){
System.out.println("Have no element.");
}
while (en != null && en.hasMoreElements()){//maybe more than one element
Object obj = en.nextElement();
if(obj instanceof SearchResult){
SearchResult si = (SearchResult) obj;
userDN += si.getName();
userDN += "," + BASEDN;
}
else{
System.out.println(obj);
}
System.out.println();
}
}catch(Exception e){
System.out.println("Exception in search():"+e);
}

return userDN;
}


public boolean authenricate(String ID,String password){
boolean valide = false;
String userDN = getUserDN(ID);

try {
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,userDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,password);
ctx.reconnect(connCtls);
System.out.println(userDN + " is authenticated");
valide = true;
}catch (AuthenticationException e) {
System.out.println(userDN + " is not authenticated");
System.out.println(e.toString());
valide = false;
}catch (NamingException e) {
System.out.println(userDN + " is not authenticated");
valide = false;
}

return valide;
}
}

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧