﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-learning java-文章分类-JNDI</title><link>http://www.blogjava.net/lmsun/category/4165.html</link><description /><language>zh-cn</language><lastBuildDate>Tue, 27 Feb 2007 12:07:43 GMT</lastBuildDate><pubDate>Tue, 27 Feb 2007 12:07:43 GMT</pubDate><ttl>60</ttl><item><title>LDAP实例</title><link>http://www.blogjava.net/lmsun/articles/17490.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Mon, 31 Oct 2005 00:57:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/17490.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/17490.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/17490.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/17490.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/17490.html</trackback:ping><description><![CDATA[<P><BR>import java.util.Properties;<BR>import javax.naming.*;&nbsp;&nbsp; <BR>import javax.naming.directory.*;<BR>/*<BR>&nbsp;* Created on 2005-10-26<BR>&nbsp;*<BR>&nbsp;* TODO To change the template for this generated file go to<BR>&nbsp;* Window - Preferences - Java - Code Style - Code Templates<BR>&nbsp;*/</P>
<P>&nbsp;</P>
<P>&nbsp;</P>
<P>class LdapAuth <BR>{<BR>public static void main(String[] args) <BR>{<BR>&nbsp;&nbsp;&nbsp; //***************** user information to be authenticated ********************************<BR>&nbsp;&nbsp;&nbsp; //*****************Please modify the following three properties accordingly ************<BR>&nbsp;&nbsp;&nbsp; String ldapHost= "<A href="ldap://aaa:389">ldap://aaa:389</A>"; //ldap host + port number<BR>&nbsp;&nbsp; String DN = "cn=admin,cn=users,dc=aa,dc=com,dc=cn";<BR>&nbsp; String password = "changeit" ;&nbsp;<BR>&nbsp;<BR>&nbsp;&nbsp;&nbsp; Properties props = new Properties();&nbsp; <BR>&nbsp;&nbsp;&nbsp; props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");&nbsp;&nbsp;&nbsp; </P>
<P>&nbsp;&nbsp;&nbsp; props.put(Context.SECURITY_AUTHENTICATION, "simple");&nbsp;&nbsp;&nbsp;&nbsp; //use simple authentication mechanism<BR>&nbsp;&nbsp;&nbsp; props.put(Context.SECURITY_PRINCIPAL, DN);&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp; props.put(Context.SECURITY_CREDENTIALS, password);&nbsp; <BR>&nbsp;&nbsp;&nbsp; props.put(Context.PROVIDER_URL, ldapHost);&nbsp; </P>
<P>&nbsp;&nbsp;&nbsp; long start = System.currentTimeMillis();<BR>&nbsp;&nbsp;&nbsp; long end=0;<BR>&nbsp;&nbsp;&nbsp; long time =0;</P>
<P>&nbsp;&nbsp;&nbsp; try <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("authenticating");&nbsp; <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DirContext ctx = new InitialDirContext(props);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("authenticated"); <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end = System.currentTimeMillis();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; time = end - start;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println( "authentication takes = " + time + " millis");&nbsp;&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("successfully authenticate DN: "+DN);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Attributes Atb = ctx.getAttributes("cn=username,ou=it,dc=aa,dc=com,dc=cn");<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NamingEnumeration enum = Atb.getAll();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("aa");<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while (enum.hasMore()) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Attribute attr = (Attribute)enum.next();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(attr);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</P>
<P>&nbsp;&nbsp;&nbsp; } <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; catch (Exception ex)<BR>&nbsp;&nbsp;&nbsp; {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end = System.currentTimeMillis();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; time = end - start;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Exception is "+ex.toString()); <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ex.printStackTrace();<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println( "authentication takes = " + time + " millis");&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("fail to authenticate DN: "+DN);<BR>&nbsp;&nbsp;&nbsp; }<BR>}<BR>}</P>
<P><BR><BR><BR><BR><BR><BR>adauth.java<BR><BR></P><PRE><FONT class=java-reserved_word><B>import</B></FONT> java.lang.*;
<FONT class=java-reserved_word><B>import</B></FONT> java.util.Hashtable ;
<FONT class=java-reserved_word><B>import</B></FONT> javax.naming.*;
<FONT class=java-reserved_word><B>import</B></FONT> javax.naming.directory.* ;
<FONT class=java-reserved_word><B>import</B></FONT> javax.naming.ldap.*;
<FONT class=java-reserved_word><B>import</B></FONT> javax.naming.spi.*;
&nbsp;
 <FONT class=java-reserved_word><B>public</B></FONT> <FONT class=java-reserved_word><B>class</B></FONT> ADAuth <FONT class=java-bracket>{</FONT>
&nbsp;
    <FONT class=java-comment>//環境設定</FONT>
    <FONT class=java-reserved_word><B>private</B></FONT> Hashtable env = <FONT class=java-reserved_word><B>null</B></FONT>;
&nbsp;
    <FONT class=java-comment>//目錄</FONT>
    DirContext ctx = <FONT class=java-reserved_word><B>null</B></FONT>;
&nbsp;
    <FONT class=java-comment>//是否能login</FONT>
    <FONT class=java-reserved_word><B>boolean</B></FONT> bLogin = <FONT class=java-reserved_word><B>false</B></FONT>;
  
    <FONT class=java-comment>//更改是否成功</FONT>
    <FONT class=java-reserved_word><B>boolean</B></FONT> getAttr = <FONT class=java-reserved_word><B>false</B></FONT>;
   
&nbsp;
  <FONT class=java-reserved_word><B>public</B></FONT> ADAuth(String strId ,String strPassword )<FONT class=java-bracket>{</FONT>
    env = <FONT class=java-reserved_word><B>new</B></FONT> Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,<FONT class=java-string>"com.sun.jndi.ldap.LdapCtxFactory"</FONT>);
    env.put(Context.PROVIDER_URL, <FONT class=java-string>"ldap://xxx.xxx.xxx.xxx:389"</FONT>);
    env.put(Context.SECURITY_AUTHENTICATION,<FONT class=java-string>"Simple"</FONT>);
    env.put(Context.SECURITY_PRINCIPAL,<FONT class=java-string>"cn="</FONT>+strId+<FONT class=java-string>",cn=users,DC=EEE,DC=abc,DC=com,DC=tw"</FONT>);
    env.put(Context.SECURITY_CREDENTIALS , strPassword );
 <FONT class=java-bracket>}</FONT><FONT class=java-comment>//end ADAuth()</FONT>
&nbsp;
  <FONT class=java-reserved_word><B>public</B></FONT> ADAuth()<FONT class=java-bracket>{</FONT>
    <FONT class=java-reserved_word><B>this</B></FONT>( <FONT class=java-string>"Administrator"</FONT> , <FONT class=java-string>"xxxxxxx"</FONT> );
  <FONT class=java-bracket>}</FONT>
&nbsp;
  <FONT class=java-reserved_word><B>public</B></FONT> <FONT class=java-reserved_word><B>boolean</B></FONT> checkAuth()<FONT class=java-bracket>{</FONT>
  &nbsp;&nbsp;
&nbsp;
    <FONT class=java-reserved_word><B>try</B></FONT><FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
      System.out.println(<FONT class=java-string>"------------------"</FONT>);
      System.out.println(<FONT class=java-string>"連入LDAP---&gt;"</FONT>);      
      ctx = <FONT class=java-reserved_word><B>new</B></FONT> InitialDirContext(env);
      System.out.println(<FONT class=java-string>"ok"</FONT>);
&nbsp;
      bLogin = <FONT class=java-reserved_word><B>true</B></FONT> ;
&nbsp;
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>catch</B></FONT>(javax.naming.AuthenticationException authe) <FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
      System.out.println(<FONT class=java-string>"失敗"</FONT>);
      bLogin = <FONT class=java-reserved_word><B>false</B></FONT> ;
      
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>catch</B></FONT>(Exception e) <FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
      System.out.println(<FONT class=java-string>"失敗"</FONT>);
      System.out.println(e);
      
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>finally</B></FONT><FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
      &nbsp;&nbsp;<FONT class=java-reserved_word><B>try</B></FONT><FONT class=java-bracket>{</FONT>
        &nbsp;&nbsp;ctx.close();
        
      &nbsp;&nbsp;<FONT class=java-bracket>}</FONT><FONT class=java-reserved_word><B>catch</B></FONT>(Exception Ignore)<FONT class=java-bracket>{</FONT><FONT class=java-bracket>}</FONT>
      
    <FONT class=java-bracket>}</FONT> 
    <FONT class=java-reserved_word><B>return</B></FONT> bLogin ;
  <FONT class=java-bracket>}</FONT>
  
  <FONT class=java-reserved_word><B>public</B></FONT> <FONT class=java-reserved_word><B>boolean</B></FONT> getAttribute(String a)<FONT class=java-bracket>{</FONT>
  &nbsp;&nbsp;
       <FONT class=java-comment>//設定要取得的attribute</FONT>
      String[] attrIds =<FONT class=java-bracket>{</FONT><FONT class=java-string>"displayName"</FONT><FONT class=java-bracket>}</FONT>;  &nbsp;&nbsp;
  &nbsp;&nbsp;
      <FONT class=java-reserved_word><B>try</B></FONT><FONT class=java-bracket>{</FONT>
  &nbsp;&nbsp;&nbsp;&nbsp;
        ctx = <FONT class=java-reserved_word><B>new</B></FONT> InitialDirContext(env);
        Attributes Atb = ctx.getAttributes(<FONT class=java-string>"cn=users,DC=EEE,DC=abc,DC=com,DC=tw"</FONT>,attrIds);
        NamingEnumeration enum = Atb.getAll();
          <FONT class=java-reserved_word><B>while</B></FONT> (enum.hasMore()) <FONT class=java-bracket>{</FONT>
              Attribute attr = (Attribute)enum.next();
              System.out.println(attr);
          <FONT class=java-bracket>}</FONT>
&nbsp;
        System.out.println(<FONT class=java-string>"------------------ok"</FONT>);
        getAttr = <FONT class=java-reserved_word><B>true</B></FONT>;
            
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>catch</B></FONT>(javax.naming.AuthenticationException authe) <FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
    &nbsp;&nbsp;System.out.println(<FONT class=java-string>"失敗"</FONT>);    &nbsp;&nbsp;
      &nbsp;&nbsp;getAttr = <FONT class=java-reserved_word><B>false</B></FONT>;
      
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>catch</B></FONT>(Exception e) <FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
    &nbsp;&nbsp;
    &nbsp;&nbsp;System.out.println(<FONT class=java-string>"失敗"</FONT>);
      &nbsp;&nbsp;getAttr = <FONT class=java-reserved_word><B>false</B></FONT>;
                System.out.println(e);
      
    <FONT class=java-bracket>}</FONT> <FONT class=java-reserved_word><B>finally</B></FONT><FONT class=java-bracket>{</FONT>
    &nbsp;&nbsp;
      &nbsp;&nbsp;<FONT class=java-reserved_word><B>try</B></FONT><FONT class=java-bracket>{</FONT>
        &nbsp;&nbsp;ctx.close();
        
      &nbsp;&nbsp;<FONT class=java-bracket>}</FONT><FONT class=java-reserved_word><B>catch</B></FONT>(Exception Ignore)<FONT class=java-bracket>{</FONT><FONT class=java-bracket>}</FONT>
    <FONT class=java-bracket>}</FONT>
    <FONT class=java-reserved_word><B>return</B></FONT> getAttr;
 <FONT class=java-bracket>}</FONT>
<FONT class=java-bracket>}</FONT>
&nbsp;
</PRE><img src ="http://www.blogjava.net/lmsun/aggbug/17490.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-31 08:57 <a href="http://www.blogjava.net/lmsun/articles/17490.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>用jdni 对LDAP读写操作代码</title><link>http://www.blogjava.net/lmsun/articles/17071.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Thu, 27 Oct 2005 08:40:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/17071.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/17071.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/17071.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/17071.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/17071.html</trackback:ping><description><![CDATA[1.连接 &nbsp;<BR>&nbsp;<BR>import &nbsp;java.util.Hashtable; &nbsp;<BR>&nbsp;<BR>import &nbsp;javax.naming.Context; &nbsp;<BR>import &nbsp;javax.naming.NamingException; &nbsp;<BR>import &nbsp;javax.naming.directory.DirContext; &nbsp;<BR>import &nbsp;javax.naming.directory.InitialDirContext; &nbsp;<BR>&nbsp;<BR>public &nbsp;class &nbsp;ActiveDirectoryConntct1 &nbsp;<BR>{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;public &nbsp;static &nbsp;void &nbsp;main(String[] &nbsp;args) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String &nbsp;account="user1"; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String &nbsp;password="password1"; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String &nbsp;root="dc=test,dc=com"; &nbsp;//root &nbsp;<BR>&nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Hashtable &nbsp;env &nbsp;= &nbsp;new &nbsp;Hashtable(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;env.put(Context.INITIAL_CONTEXT_FACTORY, &nbsp;"com.sun.jndi.ldap.LdapCtxFactory"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;env.put(Context.PROVIDER_URL, &nbsp;"ldap://192.168.0.1:389/" &nbsp;+ &nbsp;root); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;env.put(Context.SECURITY_AUTHENTICATION, &nbsp;"simple"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;env.put(Context.SECURITY_PRINCIPAL, &nbsp;"uid=" &nbsp;+ &nbsp;account &nbsp;+ &nbsp;"," &nbsp;+ &nbsp;root); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;env.put(Context.SECURITY_CREDENTIALS, &nbsp;password); &nbsp;<BR>&nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;DirContext &nbsp;ctx &nbsp;= &nbsp;null; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ctx &nbsp;= &nbsp;new &nbsp;InitialDirContext(env); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("认证成功"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;catch(javax.naming.AuthenticationException &nbsp;e) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("认证失败"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;catch(Exception &nbsp;e) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("认证出错："); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(ctx &nbsp;!= &nbsp;null) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ctx.close(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;catch &nbsp;(NamingException &nbsp;e) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//ignore &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.exit(0); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>} &nbsp;<BR>&nbsp;<BR>2.查询 &nbsp;<BR>DirContext &nbsp;ctx &nbsp;= &nbsp;... &nbsp;<BR>SearchControls &nbsp;constraints &nbsp;= &nbsp;new &nbsp;SearchControls(); &nbsp;<BR>constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); &nbsp;<BR>//constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); &nbsp;<BR>NamingEnumeration &nbsp;en &nbsp;= &nbsp;ctx.search("", &nbsp;"uid=*", &nbsp;constraints); &nbsp;//查询所有用户 &nbsp;<BR>while &nbsp;(en &nbsp;!= &nbsp;null &nbsp;&amp;&amp; &nbsp;en.hasMoreElements()) &nbsp;<BR>{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;Object &nbsp;obj &nbsp;= &nbsp;en.nextElement(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;if(obj &nbsp;instanceof &nbsp;SearchResult) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SearchResult &nbsp;si &nbsp;= &nbsp;(SearchResult) &nbsp;obj; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("name: &nbsp;" &nbsp;+ &nbsp;si.getName()); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Attributes &nbsp;attrs &nbsp;= &nbsp;si.getAttributes(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if &nbsp;(attrs &nbsp;== &nbsp;null) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("No &nbsp;attributes"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for &nbsp;(NamingEnumeration &nbsp;ae &nbsp;= &nbsp;attrs.getAll(); &nbsp;ae.hasMoreElements();) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Attribute &nbsp;attr &nbsp;= &nbsp;(Attribute) &nbsp;ae.next(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String &nbsp;attrId &nbsp;= &nbsp;attr.getID(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for &nbsp;(Enumeration &nbsp;vals &nbsp;= &nbsp;attr.getAll();vals.hasMoreElements();) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print(attrId &nbsp;+ &nbsp;": &nbsp;"); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Object &nbsp;o &nbsp;= &nbsp;vals.nextElement(); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(o &nbsp;instanceof &nbsp;byte[]) &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(new &nbsp;String((byte[])o)); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(o); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;else &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(obj); &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;<BR>&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(); &nbsp;<BR>} &nbsp;<BR>... &nbsp;<BR>ctx.close(); &nbsp;<BR>&nbsp;<BR>3.添加 &nbsp;<BR>DirContext &nbsp;ctx &nbsp;= &nbsp;...; &nbsp;<BR>String &nbsp;newUserName &nbsp;= &nbsp;"user2"; &nbsp;<BR>&nbsp;<BR>BasicAttributes &nbsp;attrs &nbsp;= &nbsp;new &nbsp;BasicAttributes(); &nbsp;<BR>&nbsp;<BR>BasicAttribute &nbsp;objclassSet &nbsp;= &nbsp;new &nbsp;BasicAttribute("objectclass"); &nbsp;<BR>objclassSet.add("person"); &nbsp; &nbsp;<BR>objclassSet.add("top"); &nbsp; &nbsp;<BR>objclassSet.add("organizationalPerson"); &nbsp; &nbsp;<BR>objclassSet.add("inetOrgPerson"); &nbsp;<BR>&nbsp;<BR>attrs.put(objclassSet); &nbsp;<BR>attrs.put("sn", &nbsp;newUserName); &nbsp;<BR>attrs.put("uid", &nbsp;newUserName); &nbsp;<BR>&nbsp;<BR>ctx.createSubcontext("uid=" &nbsp;+ &nbsp;newUserName, &nbsp;attributes); &nbsp;<BR>... &nbsp;<BR>&nbsp;<BR>&nbsp;<BR>4.删除 &nbsp;<BR>String &nbsp;account &nbsp;= &nbsp;"user2"; &nbsp;<BR>DirContext &nbsp;ctx &nbsp;= &nbsp;...; &nbsp;<BR>ctx.destroySubcontext("uid=" &nbsp;+ &nbsp;account); &nbsp;<BR>&nbsp;<BR>&nbsp;<BR>5.修改 &nbsp;<BR>String &nbsp;account &nbsp;= &nbsp;"user2"; &nbsp;<BR>String &nbsp;newDisplayName &nbsp;= &nbsp;"newDisplayName"; &nbsp;<BR>&nbsp;<BR>ModificationItem &nbsp;modificationItem[] &nbsp;= &nbsp;new &nbsp;ModificationItem[1]; &nbsp;<BR>modificationItem[0] &nbsp;= &nbsp;<BR>&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;new &nbsp;ModificationItem( &nbsp;<BR>&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;DirContext.REPLACE_ATTRIBUTE, &nbsp;<BR>&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;new &nbsp;BasicAttribute("displayName", &nbsp;newDisplayName); &nbsp;<BR>&nbsp;<BR>DirContext &nbsp;ctx &nbsp;= &nbsp;...; &nbsp;<BR>ctx.modifyAttributes("uid=" &nbsp;+ &nbsp;account, &nbsp;modificationItem);&nbsp;&nbsp;<BR><img src ="http://www.blogjava.net/lmsun/aggbug/17071.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-27 16:40 <a href="http://www.blogjava.net/lmsun/articles/17071.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>有关LDAP协议的整理(转自csdn)</title><link>http://www.blogjava.net/lmsun/articles/17067.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Thu, 27 Oct 2005 08:34:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/17067.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/17067.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/17067.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/17067.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/17067.html</trackback:ping><description><![CDATA[<SPAN id=ArticleContent1_ArticleContent1_lblContent> 
<P>    LDAP的英文全称是Lightweight Directory Access Protocol,即轻量级目录访问协议.我们<BR>知道,人们对计算机网络的使用和管理涉及了各种庞杂的资源,信息.为了提高性能,便于使<BR>用,有效管理分布式应用的服务,资源,用户及别的对象信息,这些信息需要清晰,一致地组<BR>织起来.基于这样的需求,描述各种用户,应用,文件,打印机和其它可从网络访问的资源的<BR>信息被集中到一个特殊的数据库中,这种数据库被称为目录.目录存放对象的公开或非公开的<BR>信息,这些信息以某种顺序组织,描述了每个对象的细节.电话簿,图书馆藏书卡片目录就是<BR>常见的目录.<BR>     LDAP是基于X.500标准的,访问 X.500 目录需要某种协议,例如:目录访问协议 (DAP).<BR>然而,DAP 需要大量的系统资源和支持机制来处理复杂的协议.LDAP 仅通过使用原始 X.500<BR>目录存取协议 (DAP) 的功能子集而减少了所需的系统资源消耗,而且可以根据需要定制.此<BR>外,与X.500不同,LDAP支持TCP/IP,这对访问Internet是必须的.<BR>    为了能对LDAP协议进行更好的理解,我们需要对以下概念有初步的认识:<BR>目录:Directory,存放对象的信息,这些信息以某种顺序组织,详细描述每个对象.<BR>目录信息树:DIT,Directory Information Tree,目录条目的集合构成了目录信息树.<BR>条目:Entry,目录信息树中的一个结点,是一个对象信息的集合,是目录信息中最基本的<BR>单位,包含该对象的一系列属性.<BR>属性:Attribute,属性描述对象的特征.一个属性由属性类型(type)和一个或多个属性值<BR>(values)构成.<BR>相对标识名:RDN,Relative Distinguished Name,条目的名字.<BR>唯一标识名:DN,Distinguished Name,在一个目录信息树中唯一标识一个条目的名字.<BR>    LDAP（轻量级目录访问协议，Lightweight Directory Access Protocol)是实现提供被称为目录服务的信息服务。 <BR>目录服务是一种特殊的数据库系统，其专门针对读取，浏览和搜索操作进行了特定的优化。目录一般用来包含描 <BR>述性的，基于属性的信息并支持精细复杂的过滤能力。目录一般不支持通用数据库针对大量更新操作操作需要的 <BR>复杂的事务管理或回卷策略。而目录服务的更新则一般都非常简单。这种目录可以存储包括个人信息、web链结、 <BR>jpeg图像等各种信息。为了访问存储在目录中的信息，就需要使用运行在TCP/IP之上的访问协议—LDAP。 </P>
<P>    LDAP目录中的信息是是按照树型结构组织，具体信息存储在条目(entry)的数据结构中。条目相当于关系数据库中 <BR>表的记录；条目是具有区别名DN（Distinguished Name）的属性（Attribute），DN是用来引用条目的，DN相当于 <BR>关系数据库表中的关键字（Primary Key）。属性由类型（Type）和一个或多个值（Values）组成，相当于关系数 <BR>据库中的字段（Field）由字段名和数据类型组成，只是为了方便检索的需要，LDAP中的Type可以有多个Value， <BR>而不是关系数据库中为降低数据的冗余性要求实现的各个域必须是不相关的。LDAP中条目的组织一般按照地理位置 <BR>和组织关系进行组织，非常的直观。LDAP把数据存放在文件中，为提高效率可以使用基于索引的文件数据库，而不 <BR>是关系数据库。类型的一个例子就是mail，其值将是一个电子邮件地址。 </P>
<P>WebLogic的内置的LDAP Server支持IETF LDAP为LDAPv3制定的控制访问模型。下面这个片断将讲述在内置的LDAP <BR>Server中怎样实现控制访问。可以通过编辑访问控制文件来将这些规则直接应用到目录的入口。<BR>WebLogic中的访问控制文件是acls.prop。在Server的lib中可以找到这个文件。<BR>这个文件的所有访问控制规则都被注释掉了，如果想更改这些规则，你要手工更改这个文件。<BR>注意：WebLogic Server内置的LDAP Server在默认的情况下只允许Admin帐号访问，WebLogic Server的security providers<BR>只使用Admin帐号访问内置的LDAP Server。如果你不想使用外部的LDAP Brower访问WebLogic Server的内置的LDAP Server，<BR>或者你只想使用Admin帐号访问内置的LDAP Server，你不需要编辑acls.prop文件，<BR>访问控制文件（The Access Control File）</P>
<P>访问控制文件（acls.prop）包含内置的LDAP Server的整个目录的完整的访问控制列表（ACL）。<BR>这个文件中的每一行都包含一个访问控制规则。一个访问控制规则由下面接个部分组成：<BR>    访问控制位置(Access Control Location)<BR>       每个访问控制规则都应用于LDAP目录中的一个给定的位置。这个位置通常是一个区别命名（DN），但有一个例外，这就是[root]，如果访问控制规则应用到整个目录，则只需要指定位置为[root]就可以了！<BR>       如果被访问或更改的入口的位置与访问控制规则指定的位置不相等，或在访问控制规则指定的位置的下级，则这个访问控制规则将不会被执行。</P>
<P>   访问控制范围（Access Control Scope）<BR>       访问控制范围有2种：<BR>       Entry-一个Entry范围的访问控制列表只在下面的情况下被执行：<BR>       LDAP目录的入口的DN与访问控制规则指定的位置相同。这样的规则对于包含了比并行和副入口更敏感信息的单独入口非常有用。<BR>       Subtree-意味着访问控制规则指定的位置及子树都可以适用这条规则。<BR>        如果Entry与Subtree在访问控制规则中有冲突，则Entry要优先于Subtree。</P>
<P>   访问权限（Access Rights）<BR>        访问权限应用于整个对象或对象的属性，有2个值：grant（准许）或deny（拒绝）。访问权限指定了LDAP操作的类型。<BR>   <BR>   许可(grant或deny)</P>
<P>   应用规则的属性(attribute)</P>
<P>   允许或拒绝访问的主题(subject)<BR>   在weblogic可以编写程序来访问LDAP.上手时可以选择JXplorer工具。<BR>   1.LDAP Server及LDAP Browser：<BR>      对于WLS LDAP为理解起来简单，去掉限制的方法是修改bea\weblogic81\server\lib\acls.prop文件后。修改方法：<BR>在该文件最后添加以下几行。<BR>[root]|entry#grant:s,r,o,w,c,m#[all]#public<BR>[root]|subtree#grant:s,r,o,w,c,m#[all]#public:<BR>[root]|subtree#grant:a,d,e,i,n,b,t#[entry]#public:<BR>cn=schema|entry#grant:s,r,o,w,c,m#[all]#public:<BR>cn=schema|entry#grant:a,d,e,i,n,b,t#[entry]#public:<BR>注意，该文件中这些行之间，以及其他行之间不能有空行，否则启动WLS会报错的。修改好之后就可以启动WLS了，<BR>启动后进入Console里修改Ldap Server的密码。密码修改完后需要再重新启动一次WLS。<BR>LDAP刚上手的时候没有方便的工具会很费劲。我看了CSDN上“兔八哥”的文章，用JXplorer，感觉很不错。<BR>想看这篇文章，到CSDN上搜一下“兔八哥”，系列中No.12就是关于JXplorer的配置和使用。我的连接参数如下：<BR>Host:localhost//根据实际修改<BR>Port:7001<BR>Protocol:LDAP v3<BR>Base DN:dc=ldapdomain//根据实际修改<BR>Level:User+Password<BR>User DN:cn=Admin<BR>Password:weblogic//根据实际修改<BR>.编程操作LDAP Server。<BR> 下面四个JAVA方法，分别用于初始化，查询，添加，删除，修改，关闭连接。<BR> 记得每次都需要先大概连接，操作，然后关闭连接。和使用数据库差不多。<BR> <BR>       首先是需要用到的头文件：<BR>import java.util.Hashtable;<BR>import java.util.Enumeration;<BR>import javax.naming.Context;<BR>import javax.naming.NamingException;<BR>import javax.naming.directory.DirContext;<BR>import javax.naming.directory.InitialDirContext;<BR>import javax.naming.directory.SearchControls ;<BR>import javax.naming.NamingEnumeration;<BR>import javax.naming.directory.SearchResult;<BR>import javax.naming.directory.Attributes ;<BR>import javax.naming.directory.Attribute;<BR>import javax.naming.directory.BasicAttributes;<BR>import javax.naming.directory.BasicAttribute;<BR>import javax.naming.directory.ModificationItem;<BR>import java.lang.reflect.Method;<BR>import java.io.BufferedReader;<BR>import java.io.InputStreamReader;</P>
<P><BR>然后是一个类域，用于保存上下文：<BR> <BR>DirContext ctx = null;<BR> <BR>然后是初始化：<BR> <BR>    public void init(){<BR>        String account="Admin";//操作LDAP的帐户。默认就是Admin。<BR>        String password="weblogic";//帐户Admin的密码。<BR>        String root="dc=ldapdomain"; //所操作的WLS域。也就是LDAP的根节点的DC<BR>        Hashtable env = new Hashtable();<BR>        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");//必须这样写，无论用什么LDAP服务器。<BR>        env.put(Context.PROVIDER_URL, "<A href="ldap://localhost:7001/">ldap://localhost:7001/</A>" + root);//LDAP服务器的地址:端口。对WLS端口就是7001<BR>        env.put(Context.SECURITY_AUTHENTICATION, "none");//授权界别，可以有三种授权级别，但是如果设为另外两种都无法登录，我也不知道为啥，但是只能设成这个值"none"。<BR>        env.put(Context.SECURITY_PRINCIPAL, "cn=" + account + "," + root);//载入登陆帐户和登录密码<BR>        env.put(Context.SECURITY_CREDENTIALS, password);<BR>        try{<BR>            ctx = new InitialDirContext(env);//初始化上下文<BR>            System.out.println("认证成功");//这里可以改成异常抛出。<BR>        }catch(javax.naming.AuthenticationException e){<BR>            System.out.println("认证失败");<BR>        }catch(Exception e){<BR>            System.out.println("认证出错："+e);<BR>        }<BR> }</P>
<P><BR>查询操作：<BR> <BR> public void search(){//我只能按照某些属性查找节点，偶还不会怎么查找一个目录或按照更复杂的正则式查找特定节点／目录<BR>  try{<BR>   SearchControls constraints = new SearchControls();<BR>   constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);<BR>   System.out.print("what would you want to search:");<BR>   BufferedReader bd=new BufferedReader(new InputStreamReader(System.in));<BR>   String s=bd.readLine();<BR>   NamingEnumeration en = ctx.search("", "uid="+s, constraints); //要查询的UID。如果是*则可以查到所有UID的节点<BR>   if(en == null){<BR>    System.out.println("Have no NamingEnumeration.");<BR>   }<BR>   if(!en.hasMoreElements()){<BR>    System.out.println("Have no element.");<BR>   }<BR>   while (en != null && en.hasMoreElements()){//可以查出多个元素<BR>       Object obj = en.nextElement();<BR>       if(obj instanceof SearchResult){<BR>           SearchResult si = (SearchResult) obj;<BR>           System.out.println("\tname: " + si.getName());<BR>           Attributes attrs = si.getAttributes();<BR>           if (attrs == null){<BR>               System.out.println("\tNo attributes");<BR>           }else{<BR>               for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();){//获得该节点的所有属性<BR>       Attribute attr = (Attribute) ae.next();//下一属性<BR>       String attrId = attr.getID();//获得该属性的属性名<BR>       for (Enumeration vals = attr.getAll();vals.hasMoreElements();){//获得一个属性中的所有属性值<BR>           System.out.print("\t\t"+attrId + ": ");<BR>           Object o = vals.nextElement();//下一属性值<BR>           if(o instanceof byte[])<BR>               System.out.println(new String((byte[])o));<BR>           else<BR>               System.out.println(o);<BR>       }<BR>               }<BR>           }<BR>       }<BR>       else{<BR>           System.out.println(obj);<BR>       }<BR>       System.out.println();<BR>   }<BR>  }catch(Exception e){<BR>   System.out.println("Exception in search():"+e);<BR>  }<BR>    }<BR> <BR>添加操作：<BR> <BR>    public void add(){<BR>     try{<BR>   String newUserName = "stella";<BR>   BasicAttributes attrs = new BasicAttributes();<BR>   BasicAttribute objclassSet = new BasicAttribute("objectclass");<BR>   objclassSet.add("person"); <BR>   objclassSet.add("top"); <BR>   objclassSet.add("organizationalPerson"); <BR>   objclassSet.add("inetOrgPerson");<BR>   objclassSet.add("wlsUser");<BR>   attrs.put(objclassSet);<BR>   attrs.put("sn", newUserName);<BR>   attrs.put("uid", newUserName);<BR>   attrs.put("cn", newUserName);<BR>   ctx.createSubcontext("uid=" + newUserName+",ou=people,ou=myrealm", attrs);  //添加一个节点，我还不会添加目录<BR>  }catch(Exception e){<BR>   System.out.println("Exception in add():"+e);<BR>  }<BR>    }</P>
<P><BR>修改操作：<BR> <BR>    public void edit(){<BR>     try{<BR>   String account = "stella";//修改以前旧的值<BR>   String sn = "stella sn";//修改以后新的值<BR>   ModificationItem modificationItem[] = new ModificationItem[1];<BR>   modificationItem[0] =<BR>    new ModificationItem(<BR>     DirContext.REPLACE_ATTRIBUTE,<BR>     new BasicAttribute("sn", sn));//所修改的属性<BR>   ctx.modifyAttributes("uid=" + account, modificationItem);    //执行修改操作<BR>  }catch(Exception e){<BR>   System.out.println("Exception in edit():"+e);<BR>  }<BR>    }</P>
<P><BR>删除节点操作：<BR> <BR>    public void delete(){<BR>     try{<BR>   String uid = "stella";<BR>   ctx.destroySubcontext("uid=" + uid);  //按照UID删除某个节点。我还不会删除一个目录。<BR>   }catch(Exception e){<BR>    System.out.println("Exception in edit():"+e);<BR>   }<BR>    }</P>
<P><BR>关闭连接：<BR> <BR>    public void close(){<BR>        if(ctx != null)<BR>        {<BR>            try<BR>            {<BR>                ctx.close();<BR>            }<BR>            catch (NamingException e)<BR>            {<BR>                System.out.println("NamingException in close():"+e);<BR>            }<BR>        }    <BR>    }<BR>我对LDAP的理解：它是用于对资源的管理和服务的访问协议，在Weblogic平台上的JNDI（包含EJB和DataSource)都是提供它来提供的。<BR>正是JNDI的服务和RMI结合就形成J2EE平台上分布式的应用，因此说到底层，还是LDAP协议的支持。</P></SPAN><img src ="http://www.blogjava.net/lmsun/aggbug/17067.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-27 16:34 <a href="http://www.blogjava.net/lmsun/articles/17067.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>ldap例子</title><link>http://www.blogjava.net/lmsun/articles/17065.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Thu, 27 Oct 2005 08:30:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/17065.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/17065.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/17065.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/17065.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/17065.html</trackback:ping><description><![CDATA[<TABLE cellSpacing=0 cellPadding=0 width="90%" align=center border=0>
<TBODY>
<TR>
<TD height=20>转自：<A href="http://www.webasp.net/article/13/12722_print.htm">http://www.webasp.net/article/13/12722_print.htm</A><BR><BR></TD></TR>
<TR>
<TD>/* 1. 从LDAP服务器中提取常用名cn、可区分名字uid、密码userpassword、Email地址mail <BR>* 其中使用Netscape LDAP服务器作为测试环境，使用simple认证方式登录LDAP服务器。 <BR>* 2. 用命名‘admin’密码是‘1’，整个程序使用SDK1.4.1中的JNDI标准接口。 <BR>* 3. 为了配合DOMINO数据库开发，假设用户登录时候的IP地址已经记录在了字段uid中，并用‘，’隔开 <BR>* 程序最终将打印一个包括所有用户名，密码，IP地址的字符串。 <BR>* 4. 在处理分离用户名和IP地址的时候，引入了正则表达式的使用。 <BR>*/ <BR>package mm; <BR><BR>//引入LDAP的包 <BR>import java.lang.*; <BR>import java.util.Hashtable; <BR>import java.util.Enumeration; <BR>import javax.naming.*; <BR>import javax.naming.directory.*; <BR>//import mm.splitString; <BR><BR>public class JNDISearch{ <BR>public static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory"; //驱动 <BR>public static String MY_HOST = "ldap://localhost:389"; //主机地址和端口 <BR>public static String MY_SEARCHBASE = "o=airius.com"; //基点入口 <BR>public static String MY_FILTER = "(mail=west)"; //过滤条件 <BR>public static String MGR_DN="uid=admin,ou=Administrators,ou=TopologyManagement,o=NetscapeRoot"; //用户名 <BR>public static String MGR_PW="1"; //密码 <BR>public static String MY_ATTRS[] = {/*"cn","userpassword","mail",*/"cn"}; <BR>//StringBuffer res = new StringBuffer(); //用来输入名字，IP地址的对象 <BR>public static String temp = new String(); <BR><BR><BR>public String search() throws Exception{ <BR>StringBuffer res = new StringBuffer(); <BR>try{ <BR>//建立连接 <BR>Hashtable env = new Hashtable(); <BR>env.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX); <BR>env.put(Context.PROVIDER_URL,MY_HOST); <BR>env.put(Context.SECURITY_AUTHENTICATION,"simple"); //使用简单认证来认证用户 <BR>env.put(Context.SECURITY_PRINCIPAL,MGR_DN); <BR>env.put(Context.SECURITY_CREDENTIALS,MGR_PW); <BR>DirContext ctx = new InitialDirContext(env); <BR><BR>//设置查询范围并开始查询 <BR>SearchControls constraints = new SearchControls(); <BR>constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); <BR>NamingEnumeration results = ctx.search(MY_SEARCHBASE,MY_FILTER,constraints); <BR><BR>//打印查询结果 <BR>while (results != null && results.hasMore()){ <BR>SearchResult sr = (SearchResult) results.next(); <BR>//String dn = sr.getName(); <BR>String dn = sr.getName()+","+MY_SEARCHBASE; <BR>System.out.println("=============================================="); <BR>System.out.println("Distinguished Name is: "+dn); <BR><BR>// 打印指定的字段////////////////////////////////////////////////////////////////// <BR>Attributes ar = ctx.getAttributes(dn,MY_ATTRS); <BR>if(ar==null) { <BR>//对应的uid没有多余的属性 <BR>System.out.println("Entry "+dn+" has none of the specified attributes\n"); <BR>} else { <BR>//开始显示对应的字段 <BR>for(int i=0;i<MY_ATTRS.length;i++) { <BR>Attribute attr = ar.get(MY_ATTRS[i]); <BR>if(attr!=null) { <BR>System.out.print(MY_ATTRS[i]+" : "); <BR>for(Enumeration vals = attr.getAll(); <BR>vals.hasMoreElements(); ) { <BR>temp = (String)vals.nextElement(); <BR>System.out.println("\t"+temp); <BR>res.append(temp+"/"); <BR>} <BR>} <BR>System.out.println("\n"); <BR>} <BR>/////////////////////////////////////////////////////////////////////////////////// <BR><BR><BR>/* 打印全部的字段/////////////////////////////////////////////////////////////////// <BR>Attributes attrs = sr.getAttributes(); <BR>for(NamingEnumeration ne = attrs.getAll(); <BR>ne.hasMoreElements(); ){ <BR>Attribute attr = (Attribute) ne.next(); <BR>String attrID = attr.getID(); <BR>System.out.println(attrID+": "); <BR>for(Enumeration vals = attr.getAll();vals.hasMoreElements(); ){ <BR>System.out.println("\t"+vals.nextElement()); <BR>} <BR>*////////////////////////////////////////////////////////////////////////////////// <BR>} <BR>} <BR>}catch (Exception e){ <BR>e.printStackTrace(); <BR>System.exit(1); <BR>} <BR>System.out.println(res.toString()+"\n\n\n\n"); <BR><BR>//splitString sp = new splitString(); <BR>//System.out.println("一共有"+sp.splitString(res.toString()).length+"个返回"); //打印显示结果，计算返回的数组值 <BR>//return sp.splitString(res.toString()); <BR>return res.toString(); <BR><BR>} <BR><BR>/////////////////////////////////////////////////////////////////////////////////////////// <BR>// 使用正则表达式来分拣提取的字符串 /////////////////////////////////// <BR>/////////////////////////////////////////////////////////////////////////////////////////// <BR><BR>} </TD></TR></TBODY></TABLE><img src ="http://www.blogjava.net/lmsun/aggbug/17065.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-27 16:30 <a href="http://www.blogjava.net/lmsun/articles/17065.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用 Java 對 ActiveDirectory 進行認證(转帖)</title><link>http://www.blogjava.net/lmsun/articles/16856.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Wed, 26 Oct 2005 05:09:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/16856.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/16856.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/16856.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/16856.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/16856.html</trackback:ping><description><![CDATA[
		<h3 class="heading-1">相信大部份的企業中還是以 Microsoft Exchange Server 2000 或以上版本作為公司的 EMail 服務系統，因為 Exchange Server 2000 可以快速的提供身份認證、郵件服務、行事曆、以及通訊錄服務。本篇以一個簡單的程式碼說明如何使用 Java + JNDI LDAP provider 透過 ActiveDirectory 進行身份認證。 </h3>
		<ul class="star">
				<li>其實提供身份認證服務的是 ActiveDirecory 目錄服務系統，和 Exchange Server 是沒有關係的。但是因為在建置 Exchange Server 時會透過 ActiveDirectory 目錄服務記錄使用者相關資訊，才會有 Exchange Server 可以提供身份認證的錯覺。因此以下說明的測試只需 ActiveDirectory 存在即可。 </li>
		</ul>在進行測試前，請先安裝 <span class="nobr"><img alt="&gt;&gt;" src="http://blog.t-times.net/ada/theme/images/Icon-Extlink.png" border="0" /><a href="http://java.sun.com/products/jndi/downloads/index.html">JNDI LDAP provider</a></span> 並完成所附程式的編譯作業後，即可進行測試。測試的方式為： java -cp . test.ADAuth email password 看 isLogon 結果為 true 或 false 即可。 
<p class="paragraph">完成認證後，可透過建立的 <b class="bold">目錄服務</b> 物件擷取更多的 LDAP 目錄訊息，不過目前還在測試中...<img class="jspbbEmotions" alt="" src="http://blog.t-times.net/ada/emotions/e03.gif" /></p><h3 class="heading-1-1">ADAuth.java 源碼列表</h3><div class="code"><pre><span class="java-keyword">package</span> test;<p class="paragraph"><span class="java-keyword">import</span> javax.naming.*;
<span class="java-keyword">import</span> javax.naming.directory.*;</p><p class="paragraph"><span class="java-keyword">import</span> java.util.Hashtable;</p><p class="paragraph">/**
 * 建立一個透過 ActiveDirectory 認證過的使用者物件
 *  
 * @author Ada
 */
<span class="java-keyword">public</span> class ADAuth {</p><p class="paragraph">  /**
   * @<span class="java-keyword">return</span> 認證是否通過
   */
  <span class="java-keyword">public</span><span class="java-keyword">static</span><span class="java-object">boolean</span> login( <span class="java-object">String</span> email, <span class="java-object">String</span> password ) {</p><p class="paragraph">    /** LDAP 環境變數 */
    Hashtable env = <span class="java-keyword">null</span>;</p><p class="paragraph">    /** 目錄 */
    DirContext ctx = <span class="java-keyword">null</span>;</p><p class="paragraph">    /** 認證狀態 */
    <span class="java-object">boolean</span> logged = <span class="java-keyword">true</span>;</p><p class="paragraph">    env = <span class="java-keyword">new</span> Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, <span class="java-quote">"com.sun.jndi.ldap.LdapCtxFactory"</span>);
    // 記得修改 ActiveDirectory 實際提供主機位址
    env.put( Context.PROVIDER_URL, <span class="java-quote">"ldap://active.directory.server:389"</span>);
    // 使用 username + password 進行認證
    env.put( Context.SECURITY_AUTHENTICATION, <span class="java-quote">"simple"</span> );
    // 使用者的完整 email ，也就是 AD 中的 ${sAMAccountName}@your.domain.name
    env.put( Context.SECURITY_PRINCIPAL, email );
    // 認證當時的密碼
    env.put( Context.SECURITY_CREDENTIALS, password );</p><p class="paragraph"><span class="java-keyword">try</span> {
      // 若可建立目錄物件，即表示完成登入
      ctx = <span class="java-keyword">new</span> InitialDirContext( env );
      logged = <span class="java-keyword">true</span>;
    } <span class="java-keyword">catch</span>( AuthenticationException authe ) {
      // 授權失敗
      logged = <span class="java-keyword">false</span>;
      <span class="java-object">System</span>.out.println( authe );
    } <span class="java-keyword">catch</span>( Exception e ) {
      // 不明錯誤
      <span class="java-object">System</span>.out.println( e );
    } <span class="java-keyword">finally</span> {
      <span class="java-keyword">try</span> {
        // 記得把目錄關閉
        ctx.close();
      } <span class="java-keyword">catch</span> ( Exception Ignore ) { }
    }</p><p class="paragraph"><span class="java-keyword">return</span> logged;
  }</p><p class="paragraph">  /**
   * 主執行程序
   * @author Ada
   */
  <span class="java-keyword">public</span><span class="java-keyword">static</span> void main( <span class="java-object">String</span>[] args ) {</p><p class="paragraph">    // 一定要 email + 密碼才能登入		
    <span class="java-keyword">if</span>( args.length == 2 ) {
      <span class="java-object">System</span>.out.println( <span class="java-quote">"is Logon? : "</span> + login( args[0], args[1] );
    } <span class="java-keyword">else</span> {
      <span class="java-object">System</span>.out.println( <span class="java-quote">"EMail/Password not initialed!"</span> );
    }
  }
}<br /><br />另一例:<br /><br />/*<br /> * ADAuth.java<br /> *<br /> * Created on 2004年9月29日, 上午 11:37<br /> */<br />import java.util.Hashtable;<br />import javax.naming.Context;<br />import javax.naming.AuthenticationException;<br />import javax.naming.directory.DirContext;<br />import javax.naming.directory.InitialDirContext;<br />/**<br /> *<br /> * @author  ajax<br /> */<br />public class ADAuth {<br />    DirContext ctx = null;<br />    Hashtable env = null;<br />    /** Creates a new instance of ADAuth */<br />    public ADAuth(String acct,String password) {<br />        env = new Hashtable();<br />        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");<br />        /*<br />         * Ldap://後可接active directory的server名稱或ip,port可以不用key,預設為389<br />         */<br />        env.put(Context.PROVIDER_URL,"Ldap://192.168.1.16:389");<br />        env.put(Context.SECURITY_AUTHENTICATION, "simple");<br />        /*<br />         * 公司網域為 company.com.tw<br />         *<br />         * 所以有這一段 DC=company,DC=com,DC=tw<br />         */<br />        env.put(Context.SECURITY_PRINCIPAL,"cn="+acct+",cn=users,DC=公司AD的網域名");//,DC=com,DC=tw");<br />        env.put(Context.SECURITY_CREDENTIALS,password);<br />        try{<br />            ctx = new InitialDirContext(env);<br />            System.out.println("驗証通過");<br />        }catch(AuthenticationException authe){<br />            System.out.println("驗証失敗");<br />        }catch(Exception e){<br />            System.out.println(e);<br />        }finally{<br />            try{<br />                ctx.close();<br />            }catch(Exception Ignore){}<br />        }<br />     }<br />      public static void main(String[] args){<br />          new ADAuth("帳號","密碼");<br />      }<br />}<br /></p></pre></div><img src ="http://www.blogjava.net/lmsun/aggbug/16856.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-26 13:09 <a href="http://www.blogjava.net/lmsun/articles/16856.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>JNDI基础</title><link>http://www.blogjava.net/lmsun/articles/16782.html</link><dc:creator>my java</dc:creator><author>my java</author><pubDate>Tue, 25 Oct 2005 09:23:00 GMT</pubDate><guid>http://www.blogjava.net/lmsun/articles/16782.html</guid><wfw:comment>http://www.blogjava.net/lmsun/comments/16782.html</wfw:comment><comments>http://www.blogjava.net/lmsun/articles/16782.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/lmsun/comments/commentRss/16782.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/lmsun/services/trackbacks/16782.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: JNDI是java访问名字和目录服务的接口，与JDBC一样，它仅仅只定义了一套服务接口，实现由具体厂商提供。作为j2ee核心组件之一，它为应用程序查找其他程序组件和资源提供了统一的接口，其中最常见的用途就是数据源的配置、EJB名字查找、JMS相关配置等。JNDI的架构如下图。在JDK1.3中，已经包含了JNDI，它分成五个包。每个包提供的功能： -          javax.naming，...&nbsp;&nbsp;<a href='http://www.blogjava.net/lmsun/articles/16782.html'>阅读全文</a><img src ="http://www.blogjava.net/lmsun/aggbug/16782.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/lmsun/" target="_blank">my java</a> 2005-10-25 17:23 <a href="http://www.blogjava.net/lmsun/articles/16782.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>