KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > users > authenticate > LdapAuthenticator


1 /*
2  * Created on Jul 20, 2006
3  */

4 package com.openedit.users.authenticate;
5
6 import java.util.Properties JavaDoc;
7
8 import javax.naming.Context JavaDoc;
9 import javax.naming.NameAlreadyBoundException JavaDoc;
10 import javax.naming.directory.DirContext JavaDoc;
11 import javax.naming.directory.InitialDirContext JavaDoc;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15
16 import com.openedit.users.Authenticator;
17 import com.openedit.users.User;
18 import com.openedit.users.UserManagerException;
19
20 public class LdapAuthenticator implements Authenticator
21 {
22     private static final Log log = LogFactory.getLog(LdapAuthenticator.class);
23     protected String JavaDoc fieldServer;
24     
25     public boolean authenticate(User inUser, String JavaDoc inPassword) throws UserManagerException
26     {
27
28          Properties JavaDoc env = new Properties JavaDoc();
29          
30          env.put( Context.INITIAL_CONTEXT_FACTORY,
31                   "com.sun.jndi.ldap.LdapCtxFactory" );
32          String JavaDoc ldapserver = inUser.getString("ldapserver");
33          if( ldapserver == null)
34          {
35             ldapserver = getServer();
36          }
37          if( !ldapserver.startsWith("ldap://"))
38          {
39              ldapserver = "ldap://" + ldapserver + "/";
40          }
41          env.put( Context.PROVIDER_URL, ldapserver);
42
43          env.put( Context.SECURITY_PRINCIPAL, inUser.getUserName() );
44          env.put( Context.SECURITY_CREDENTIALS, inPassword );
45          
46          try {
47                  // obtain initial directory context using the environment
48
DirContext JavaDoc ctx = new InitialDirContext JavaDoc( env );
49                  
50                  // now, create the root context, which is just a subcontext
51
// of this initial directory context.
52
//ctx.createSubcontext( rootContext );
53
} catch ( NameAlreadyBoundException JavaDoc nabe ) {
54                  log.error("LDAP has already been bound!" );
55                  return false;
56          } catch ( Exception JavaDoc e ) {
57                  log.error( e );
58                  return false;
59          }
60          return true;
61     }
62
63     public String JavaDoc getServer()
64     {
65         return fieldServer;
66     }
67
68     public void setServer(String JavaDoc inServer)
69     {
70         fieldServer = inServer;
71     }
72 }
Popular Tags