java ad登录_Ldap登陆AD(Active Directory)进行认证的Java示例

packageLdapTest;importjava.util.Hashtable;importjavax.naming.Context;importjavax.naming.NamingEnumeration;importjavax.naming.NamingException;importjavax.naming.AuthenticationException;importjavax.naming.directory.SearchControls;importjavax.naming.directory.SearchResult;importjavax.naming.ldap.Control;importjavax.naming.ldap.InitialLdapContext;importjavax.naming.ldap.LdapContext;public classAuthenticationTest {private String BASE_DN ="dc=statestreet,dc=com";//private DirContext ctx = null;

private LdapContext ctx = null;private Hashtable env = null;private Control[] connCtls = null;private voidLdapConnect(){

env= newHashtable();

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

env.put(Context.PROVIDER_URL,");

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

env.put(Context.SECURITY_PRINCIPAL,"cn=Manager,dc=statestreet,dc=com");

env.put(Context.SECURITY_CREDENTIALS,"****"); //自己填入

try{

ctx= newInitialLdapContext(env,connCtls);//ctx = new InitialDirContext(env);

System.out.println("Login Ldap Server Successful...");

}catch(AuthenticationException e){

System.out.println("Login Ldap Server Failed...");

e.printStackTrace();

}catch(Exception e){

System.out.println("Login Ldap Server Wrong...\n "+e.toString());

}

}privateString getUserDN(String userid){

String userDN="";try{

SearchControls constraints= newSearchControls();

constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

NamingEnumeration en= ctx.search("","uid="+userid,constraints);if(en == null){

System.out.println("Have NO such user!");

}if(!en.hasMoreElements()){

System.out.println("Have NO such user!");

}while (en != null &&en.hasMoreElements()){

Object obj=en.nextElement();if(obj instanceofSearchResult){

SearchResult si=(SearchResult) obj;

userDN+=si.getName();

userDN+= "," +BASE_DN;

}else{

System.out.println(obj);

}

}

}catch(Exception e){

System.out.println("Exception in search user DN : "+e.toString());

}returnuserDN;

}public booleanAuthenricate(String ID,String pwd){

LdapConnect();boolean valide = false;

String userDN=getUserDN(ID);if(userDN=="")returnvalide;try{

ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,userDN);

ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,pwd);

ctx.reconnect(connCtls);

System.out.println(userDN+ " is authenticated! ");

valide= true;

}catch(AuthenticationException e) {

System.out.println(userDN+ " is NOT authenticated! ");

valide= false;

}catch(NamingException e) {

System.out.println(userDN+ " is NOT authenticated! ");

valide= false;

}

LdapDisconnect();returnvalide;

}private voidLdapDisconnect(){if (ctx != null) {try{

ctx.close();

}catch(NamingException e) {

e.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值