LDAP SSL

引用:http://www.experts-exchange.com/Programming/Languages/Java/New_to_Java/Q_24254611.html


package beans;

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;



public class TestLdapScript {


@SuppressWarnings("unchecked")
public static void main(String[] args) {

Hashtable env = new Hashtable();

String userName = "username";
String passWord = "password";
String ldap = "ldap://xx.xxxxx.net:636";

String keystore = "Program Files (x86)/Java/jre1.6.0_06/lib/security";
System.setProperty("javax.net.ssl.trustStroe", keystore);

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



env.put(Context.SECURITY_AUTHENTICATION,"simple"); //No other SALS worked with me
env.put(Context.SECURITY_PRINCIPAL,userName); // specify the username ONLY to let Microsoft Happy
env.put(Context.SECURITY_CREDENTIALS, passWord); //the password

env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.PROVIDER_URL,ldap);


try {


DirContext ctx = new InitialLdapContext(env,null);
//Create the search controls
SearchControls searchCtls = new SearchControls();

//Specify the attributes to return
String returnedAtts[]={"sn","givenName"};
searchCtls.setReturningAttributes(returnedAtts);

//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

//specify the LDAP search filter
//String searchFilter = "(&(ObjectClass=Person)(!(ObjectClass=user)))";
//String searchFilter = "(&(objectClass=user)(&(objectClass=Person)(!(userAccountControl=514))))";
String searchFilter = "(&(objectClass=user)(mail=*))";

//Specify the Base for the search
String searchBase = "DC=xx,DC=net";

//initialize counter to total the results
int totalResults = 0;


// Search for objects using the filter
NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

//Loop through the search results
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();

totalResults++;

System.out.println(">>>" + "Test>>" + sr );

// Print out some of the attributes, catch the exception if the attributes have no values

/* Attributes attrs = sr.getAttributes();
if (attrs != null) {
try {
System.out.println(" surname: " + attrs.get("cn").get());
System.out.println(" firstname: " + attrs.get("DisplayName").get());


}
catch (NullPointerException e) {
System.out.println("Errors listing attributes: " + e);
}
}*/


}

ctx.close();
} catch(NamingException e)
{
System.err.println(e);
return;
} //if no exception, the user is already authenticated.
System.out.println("OK, successfully authenticating user");
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值