You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@lenya.apache.org by Markus Anwander <po...@poison.ch> on 2004/10/12 18:38:00 UTC

LDAPUser.java LDAP Access

Hello

If somebody is interested in:
I modified src/java/org/apache/lenya/ac/ldap/LDAPUser.java to allow  
anonymous
connections to LDAP-Server (original LDAPUser.java did not worked for  
me) and to find Users DN with
only knowing their uid (without this ou=people).

It was also nessesary to modify config/ac/passwd/ldap.properties

PS
I didn't modify/FIX the existsUser(String ldapId) method....


----------------------------------------------------------------------
src/java/org/apache/lenya/ac/ldap/LDAPUser.java

/*
  * Copyright 1999-2004 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License"); you  
may not use this file except
  * in compliance with the License. You may obtain a copy of the License  
at
  *
  * http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software  
distributed under the License
  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS  
OF ANY KIND, either express
  * or implied. See the License for the specific language governing  
permissions and limitations under
  * the License.
  *
  */

package org.apache.lenya.ac.ldap;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.lenya.ac.AccessControlException;
import org.apache.lenya.ac.file.FileUser;

import com.sun.jndi.ldap.LdapCtxFactory;

/**
  * LDAP user.
  * @version $Id$
  */
public class LDAPUser extends FileUser {
     private static Properties defaultProperties = null;

     protected static final String LDAP_ID = "ldapid";
     private static String PROVIDER_URL = "provider-url";
     private static String MGR_DN = "mgr-dn";
     private static String MGR_PW = "mgr-pw";
     private static String PARTIAL_USER_DN = "partial-user-dn";
     private static String KEY_STORE = "key-store";
     private static String SECURITY_PROTOCOL = "security-protocol";
     private static String SECURITY_AUTHENTICATION =  
"security-authentication";
     private static String BASE_DN = "base-dn";
     private static String USER_ATTR = "usr-attr";
     private static String AUTH_TYPE_USER = "user-authentication";
     private String ldapId;

     private String ldapName;

     /**
      * Creates a new LDAPUser object.
      */
     public LDAPUser() {
     }

     /**
      * Creates a new LDAPUser object.
      * @param configurationDirectory The configuration directory.
      */
     public LDAPUser(File configurationDirectory) {
         setConfigurationDirectory(configurationDirectory);
     }

     /**
      * Create an LDAPUser.
      *
      * @param configurationDirectory where the user will be attached to
      * @param id user id of LDAPUser
      * @param email of LDAPUser
      * @param ldapId of LDAPUser
      * @throws ConfigurationException if the properties could not be  
read
      */
     public LDAPUser(File configurationDirectory, String id, String  
email, String ldapId)
             throws ConfigurationException {
         super(configurationDirectory, id, null, email, null);
         this.ldapId = ldapId;

         initialize();
     }

     /**
      * Create a new LDAPUser from a configuration
      *
      * @param config the <code>Configuration</code> specifying the user  
details
      * @throws ConfigurationException if the user could not be  
instantiated
      */
     public void configure(Configuration config) throws  
ConfigurationException {
         super.configure(config);
         ldapId = config.getChild(LDAP_ID).getValue();

         initialize();
     }

     /**
      * Checks if a user exists.
      * @param ldapId The LDAP id.
      * @return A boolean value.
      * @throws AccessControlException when an error occurs. FIXME: This  
method does not work.
      */
     public boolean existsUser(String ldapId) throws  
AccessControlException {

         boolean exists = false;
         LdapContext context = null;

         try {
             readProperties();

             context = bind(defaultProperties.getProperty(MGR_DN),  
defaultProperties
                     .getProperty(MGR_PW));

             String peopleName = "ou=People";
             Attributes attributes = new BasicAttributes("uid", ldapId);
             NamingEnumeration enumeration = context.search(peopleName,  
attributes);

             exists = enumeration.hasMoreElements();
         } catch (Exception e) {
             throw new AccessControlException("Exception during search:  
", e);
         } finally {
             try {
                 if (context != null) {
                     close(context);
                 }
             } catch (NamingException e) {
                 throw new AccessControlException("Closing context  
failed: ", e);
             }
         }
         return exists;
     }

     /**
      * Initializes this user.
      *
      * @throws ConfigurationException when something went wrong.
      */
     protected void initialize() throws ConfigurationException {
         LdapContext context = null;
         try {
             readProperties();

             String name = null;
             context = bind(defaultProperties.getProperty(MGR_DN),  
defaultProperties.getProperty(MGR_PW));

         } catch (Exception e) {
             throw new ConfigurationException("Could not read  
properties", e);
         } finally {
             try {
                 if (context != null) {
                     close(context);
                 }
             } catch (NamingException e) {
                 throw new ConfigurationException("Closing context  
failed: ", e);
             }
         }
     }

     /**
      * @see org.apache.lenya.ac.file.FileUser#createConfiguration()
      */
     protected Configuration createConfiguration() {
         DefaultConfiguration config = (DefaultConfiguration)  
super.createConfiguration();

         // add ldap_id node
         DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
         child.setValue(ldapId);
         config.addChild(child);

         return config;
     }

     /**
      * Get the ldap id
      *
      * @return the ldap id
      */
     public String getLdapId() {
         return ldapId;
     }

     /**
      * Set the ldap id
      *
      * @param string the new ldap id
      */
     public void setLdapId(String string) {
         ldapId = string;
     }

     /**
      * (non-Javadoc)
      *
      * @see org.apache.lenya.ac.User#authenticate(java.lang.String)
      */
     public boolean authenticate(String password) {

         Context ctx = null;
		boolean authenticated = false;
		String principal = new String("");
		
		
		try {
			readProperties();
			principal = searchDN(this.getLdapId(),  
defaultProperties.getProperty(MGR_DN),  
defaultProperties.getProperty(MGR_PW) );
			ctx = bind(principal, password,  
defaultProperties.getProperty(AUTH_TYPE_USER));
			authenticated = true;
			close(ctx);

			if (getLogger().isDebugEnabled()) {
                 getLogger().debug("Context closed.");
             }
			
         } catch (NamingException e) {
             // log this failure
             // StringWriter writer = new StringWriter();
             // e.printStackTrace(new PrintWriter(writer));
             if (getLogger().isInfoEnabled()) {
                 getLogger().info("Bind for user " + principal + " to  
Ldap server failed: ", e);
             }
         }
		
		catch(IOException e){
             // log this failure
             // StringWriter writer = new StringWriter();
             // e.printStackTrace(new PrintWriter(writer));
            if (getLogger().isInfoEnabled()) {
                 getLogger().info("Can not read properties from File  
config/ac/passwd/ldap.properties ", e);
             }
         }
         return authenticated;
     }

     /**
      * @see org.apache.lenya.ac.Item#getName()
      */
     public String getName() {
         return ldapName;
     }

     /**
      * LDAP Users fetch their name information from the LDAP server, so  
we don't store it locally.
      * Since we only have read access we basically can't set the name,  
i.e. any request to change
      * the name is ignored.
      *
      * @param string is ignored
      */
     public void setName(String string) {
         // we do not have write access to LDAP, so we ignore
         // change request to the name.
     }

     /**
      * The LDAPUser doesn't store any passwords as they are handled by  
LDAP
      *
      * @param plainTextPassword is ignored
      */
     public void setPassword(String plainTextPassword) {
         setEncryptedPassword(null);
     }

     /**
      * The LDAPUser doesn't store any passwords as they are handled by  
LDAP
      *
      * @param encryptedPassword is ignored
      */
     protected void setEncryptedPassword(String encryptedPassword) {
         encryptedPassword = null;
     }
	
	
     /**
      * Connect to the LDAP server
      *
      * @param principal the principal string for the LDAP connection
      * @param credentials the credentials for the LDAP connection
      * @return a <code>LdapContext</code>
      * @throws NamingException if there are problems establishing the  
Ldap connection
      */
     private LdapContext bind(String principal, String credentials)  
throws NamingException {
		return this.bind(principal, credentials,  
defaultProperties.getProperty(SECURITY_AUTHENTICATION));
		}
	

     /**
      * Connect to the LDAP server
      *
      * @param principal the principal string for the LDAP connection
      * @param credentials the credentials for the LDAP connection
      * @param authMethod Authentication Method (simple or none)
      * @return a <code>LdapContext</code>
      * @throws NamingException if there are problems establishing the  
Ldap connection
      */
     private LdapContext bind(String principal, String credentials,  
String authMethod ) throws NamingException {

        getLogger().info("Binding principal: [" + principal + "]");

         Hashtable env = new Hashtable();

         System.setProperty("javax.net.ssl.trustStore",  
getConfigurationDirectory()
                 .getAbsolutePath()
                 + File.separator +  
defaultProperties.getProperty(KEY_STORE));
				
				
		if(authMethod.equals("none")){
			env.put(Context.PROVIDER_URL,  
defaultProperties.getProperty(PROVIDER_URL) );
			env.put(Context.SECURITY_AUTHENTICATION, "none");
			env.put(Context.SECURITY_PROTOCOL, "ssl");
			 
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactor 
y");
		}
		else {
			env.put(Context.INITIAL_CONTEXT_FACTORY,  
LdapCtxFactory.class.getName());
			env.put(Context.PROVIDER_URL,  
defaultProperties.getProperty(PROVIDER_URL));
			env.put(Context.SECURITY_PROTOCOL,  
defaultProperties.getProperty(SECURITY_PROTOCOL));
			env.put(Context.SECURITY_AUTHENTICATION, authMethod);
			env.put(Context.SECURITY_PRINCIPAL, principal);
			env.put(Context.SECURITY_CREDENTIALS, credentials);
		}
         LdapContext ctx = new InitialLdapContext(env, null);

        getLogger().info("Finished binding principal.");

         return ctx;
     }

     /**
      * Close the connection to the LDAP server
      *
      * @param ctx the context that was returned from the bind
      * @throws NamingException if there is a problem communicating to  
the LDAP server
      */
     private void close(Context ctx) throws NamingException {
         ctx.close();
     }

     /**
      * Read the properties
      *
      * @throws IOException if the properties cannot be found.
      */
     private void readProperties() throws IOException {
         // create and load default properties
         File propertiesFile = new File(getConfigurationDirectory(),  
"ldap.properties");

         if (defaultProperties == null) {
             defaultProperties = new Properties();

             FileInputStream in = null;
             try {
                 in = new FileInputStream(propertiesFile);
                 defaultProperties.load(in);
             } finally {
                 if (in != null) {
                     in.close();
                 }
             }
         }
     }
	
     /**
      * Search DN in LDAP
      *
      * @param user Lenya-Users name
      * @param bindUser manager-username for simple LDAP connection
      * @param bindPw manger-password for simple LDAP connection
      * @return a <code>Lenya-Users LDAP DN</code
      * @throws NamingException if there are problems establishing the  
Ldap connection
	 */
     private String searchDN(String user, String bindUser, String  
bindPw) throws NamingException {
				
			String principal = new String("");
			LdapContext searchCtx = null;
			searchCtx= bind(bindUser, bindPw);

			// Set Scope
			SearchControls scope = new SearchControls();
			scope.setSearchScope(SearchControls.SUBTREE_SCOPE);

			NamingEnumeration results =  
searchCtx.search(defaultProperties.getProperty(BASE_DN),
														"("+defaultProperties.getProperty(USER_ATTR)+"="+user+")",
														scope );
														
			while (results != null && results.hasMore()) {
				SearchResult si = (SearchResult) results.next();
				principal = si.getName();
				if(si.isRelative()) {
					if (principal.length()>0) principal = principal +","+  
defaultProperties.getProperty(BASE_DN);
				}
				if (getLogger().isDebugEnabled()) {
					getLogger().debug("Authenticating with principal [" + principal +  
"]");
				}
			}
			close(searchCtx);
			return principal;
		}
}


----------------------------------------------------------------------
config/ac/passwd/ldap.properties


### LDAP URL
provider-url=ldaps://ldap.foodomain.com:636/

### Normal Authentication #######################
### Manager which is allowed to retrieve a list of "all" users  
(fullname) from LDAP server
# mgr-dn=cn=proxyauth,ou=People,ou=FooOrg,dc=foodomain,dc=com
### Manager Password
# mgr-pw=sekret
# security-authentication=simple

### Anonymous Authentication ####################
mgr-dn=anonymous
mgr-pw=none
security-authentication=none

### Base DN, Lenya-User have to be in this Folder or a Subfolder
base-dn=dc=foodomain,dc=com

### keystore is taken relatively to the publication config/ac directory
key-store=.keystore
security-protocol=ssl

### Attribute-name of User Partition (Lenya-User)
usr-attr=uid

### Authentication for Lenya-User
user-authentication=simple

-- 
========================================
Markus Anwander
University of Berne
markus.anwander@id.unibe.ch

Re: LDAPUser.java LDAP Access

Posted by Markus Anwander <ma...@id.unibe.ch>.
> > 
> > Hello
> > 
> > If somebody is interested in:
> > I modified src/java/org/apache/lenya/ac/ldap/LDAPUser.java to allow  
> > anonymous
> > connections to LDAP-Server (original LDAPUser.java did not worked for  
> > me) 
> 
> Anonymous connections work for me without any code change, I just leave
>   mgr-dn=
>   mgr-pw=
> in the ldap.properties (that is, empty)
> 

Yes i tried it this way but it was not possible to make Anonymous connections. 
 
> > and to find Users DN with
> > only knowing their uid (without this ou=people).
> 
> Whatever follows the username should be defined on the
>   partial-user-dn=
> line in the ldap.properties
> There shouldn't be anything about "ou=..." in the Java source code.
> Or did I misunderstand you ?
> 

Perhaps i misunderstand the Code ;-) 
>From my point of view, its only possible to connect users with the same DN 
(partial-user-dn).
But we have many different DNs (different name, length) 





> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: lenya-user-unsubscribe@cocoon.apache.org
> For additional commands, e-mail: lenya-user-help@cocoon.apache.org
> 
> 


-- 
========================================
Markus Anwander
University of Berne
markus.anwander@id.unibe.ch

------------------------------------------------------
This mail was sent through IMP at http://mail.unibe.ch


---------------------------------------------------------------------
To unsubscribe, e-mail: lenya-user-unsubscribe@cocoon.apache.org
For additional commands, e-mail: lenya-user-help@cocoon.apache.org


Re: LDAPUser.java LDAP Access

Posted by Wolfgang Kaltz <jw...@yahoo.com>.
Markus Anwander <poison <at> poison.ch> writes:

> 
> Hello
> 
> If somebody is interested in:
> I modified src/java/org/apache/lenya/ac/ldap/LDAPUser.java to allow  
> anonymous
> connections to LDAP-Server (original LDAPUser.java did not worked for  
> me) 

Anonymous connections work for me without any code change, I just leave
  mgr-dn=
  mgr-pw=
in the ldap.properties (that is, empty)


> and to find Users DN with
> only knowing their uid (without this ou=people).

Whatever follows the username should be defined on the
  partial-user-dn=
line in the ldap.properties
There shouldn't be anything about "ou=..." in the Java source code.
Or did I misunderstand you ?




---------------------------------------------------------------------
To unsubscribe, e-mail: lenya-user-unsubscribe@cocoon.apache.org
For additional commands, e-mail: lenya-user-help@cocoon.apache.org


Re: LDAPUser.java LDAP Access

Posted by Torsten Schlabach <TS...@gmx.net>.
Hello,

I am interested in that. Thank you. You might be interested in posting the
patch on the developers list to it may get into the codebase.

If you got some more time you might also be interested in rewriting the
whole LDAP auth. There have been a lot of discussions; I can give you
references if you are interested in this.

Torsten

> Hello
> 
> If somebody is interested in:
> I modified src/java/org/apache/lenya/ac/ldap/LDAPUser.java to allow  
> anonymous
> connections to LDAP-Server (original LDAPUser.java did not worked for  
> me) and to find Users DN with
> only knowing their uid (without this ou=people).
> 
> It was also nessesary to modify config/ac/passwd/ldap.properties
> 
> PS
> I didn't modify/FIX the existsUser(String ldapId) method....
> 
> 
> ----------------------------------------------------------------------
> src/java/org/apache/lenya/ac/ldap/LDAPUser.java
> 
> /*
>   * Copyright 1999-2004 The Apache Software Foundation
>   *
>   * Licensed under the Apache License, Version 2.0 (the "License"); you  
> may not use this file except
>   * in compliance with the License. You may obtain a copy of the License  
> at
>   *
>   * http://www.apache.org/licenses/LICENSE-2.0
>   *
>   * Unless required by applicable law or agreed to in writing, software  
> distributed under the License
>   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS  
> OF ANY KIND, either express
>   * or implied. See the License for the specific language governing  
> permissions and limitations under
>   * the License.
>   *
>   */
> 
> package org.apache.lenya.ac.ldap;
> 
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.IOException;
> import java.util.Hashtable;
> import java.util.Properties;
> 
> import javax.naming.Context;
> import javax.naming.NamingEnumeration;
> import javax.naming.NamingException;
> import javax.naming.directory.Attribute;
> import javax.naming.directory.Attributes;
> import javax.naming.directory.BasicAttributes;
> import javax.naming.directory.SearchControls;
> import javax.naming.directory.SearchResult;
> import javax.naming.ldap.InitialLdapContext;
> import javax.naming.ldap.LdapContext;
> 
> import org.apache.avalon.framework.configuration.Configuration;
> import org.apache.avalon.framework.configuration.ConfigurationException;
> import org.apache.avalon.framework.configuration.DefaultConfiguration;
> import org.apache.lenya.ac.AccessControlException;
> import org.apache.lenya.ac.file.FileUser;
> 
> import com.sun.jndi.ldap.LdapCtxFactory;
> 
> /**
>   * LDAP user.
>   * @version $Id$
>   */
> public class LDAPUser extends FileUser {
>      private static Properties defaultProperties = null;
> 
>      protected static final String LDAP_ID = "ldapid";
>      private static String PROVIDER_URL = "provider-url";
>      private static String MGR_DN = "mgr-dn";
>      private static String MGR_PW = "mgr-pw";
>      private static String PARTIAL_USER_DN = "partial-user-dn";
>      private static String KEY_STORE = "key-store";
>      private static String SECURITY_PROTOCOL = "security-protocol";
>      private static String SECURITY_AUTHENTICATION =  
> "security-authentication";
>      private static String BASE_DN = "base-dn";
>      private static String USER_ATTR = "usr-attr";
>      private static String AUTH_TYPE_USER = "user-authentication";
>      private String ldapId;
> 
>      private String ldapName;
> 
>      /**
>       * Creates a new LDAPUser object.
>       */
>      public LDAPUser() {
>      }
> 
>      /**
>       * Creates a new LDAPUser object.
>       * @param configurationDirectory The configuration directory.
>       */
>      public LDAPUser(File configurationDirectory) {
>          setConfigurationDirectory(configurationDirectory);
>      }
> 
>      /**
>       * Create an LDAPUser.
>       *
>       * @param configurationDirectory where the user will be attached to
>       * @param id user id of LDAPUser
>       * @param email of LDAPUser
>       * @param ldapId of LDAPUser
>       * @throws ConfigurationException if the properties could not be  
> read
>       */
>      public LDAPUser(File configurationDirectory, String id, String  
> email, String ldapId)
>              throws ConfigurationException {
>          super(configurationDirectory, id, null, email, null);
>          this.ldapId = ldapId;
> 
>          initialize();
>      }
> 
>      /**
>       * Create a new LDAPUser from a configuration
>       *
>       * @param config the <code>Configuration</code> specifying the user  
> details
>       * @throws ConfigurationException if the user could not be  
> instantiated
>       */
>      public void configure(Configuration config) throws  
> ConfigurationException {
>          super.configure(config);
>          ldapId = config.getChild(LDAP_ID).getValue();
> 
>          initialize();
>      }
> 
>      /**
>       * Checks if a user exists.
>       * @param ldapId The LDAP id.
>       * @return A boolean value.
>       * @throws AccessControlException when an error occurs. FIXME: This  
> method does not work.
>       */
>      public boolean existsUser(String ldapId) throws  
> AccessControlException {
> 
>          boolean exists = false;
>          LdapContext context = null;
> 
>          try {
>              readProperties();
> 
>              context = bind(defaultProperties.getProperty(MGR_DN),  
> defaultProperties
>                      .getProperty(MGR_PW));
> 
>              String peopleName = "ou=People";
>              Attributes attributes = new BasicAttributes("uid", ldapId);
>              NamingEnumeration enumeration = context.search(peopleName,  
> attributes);
> 
>              exists = enumeration.hasMoreElements();
>          } catch (Exception e) {
>              throw new AccessControlException("Exception during search:  
> ", e);
>          } finally {
>              try {
>                  if (context != null) {
>                      close(context);
>                  }
>              } catch (NamingException e) {
>                  throw new AccessControlException("Closing context  
> failed: ", e);
>              }
>          }
>          return exists;
>      }
> 
>      /**
>       * Initializes this user.
>       *
>       * @throws ConfigurationException when something went wrong.
>       */
>      protected void initialize() throws ConfigurationException {
>          LdapContext context = null;
>          try {
>              readProperties();
> 
>              String name = null;
>              context = bind(defaultProperties.getProperty(MGR_DN),  
> defaultProperties.getProperty(MGR_PW));
> 
>          } catch (Exception e) {
>              throw new ConfigurationException("Could not read  
> properties", e);
>          } finally {
>              try {
>                  if (context != null) {
>                      close(context);
>                  }
>              } catch (NamingException e) {
>                  throw new ConfigurationException("Closing context  
> failed: ", e);
>              }
>          }
>      }
> 
>      /**
>       * @see org.apache.lenya.ac.file.FileUser#createConfiguration()
>       */
>      protected Configuration createConfiguration() {
>          DefaultConfiguration config = (DefaultConfiguration)  
> super.createConfiguration();
> 
>          // add ldap_id node
>          DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
>          child.setValue(ldapId);
>          config.addChild(child);
> 
>          return config;
>      }
> 
>      /**
>       * Get the ldap id
>       *
>       * @return the ldap id
>       */
>      public String getLdapId() {
>          return ldapId;
>      }
> 
>      /**
>       * Set the ldap id
>       *
>       * @param string the new ldap id
>       */
>      public void setLdapId(String string) {
>          ldapId = string;
>      }
> 
>      /**
>       * (non-Javadoc)
>       *
>       * @see org.apache.lenya.ac.User#authenticate(java.lang.String)
>       */
>      public boolean authenticate(String password) {
> 
>          Context ctx = null;
> 		boolean authenticated = false;
> 		String principal = new String("");
> 		
> 		
> 		try {
> 			readProperties();
> 			principal = searchDN(this.getLdapId(),  
> defaultProperties.getProperty(MGR_DN),  
> defaultProperties.getProperty(MGR_PW) );
> 			ctx = bind(principal, password,  
> defaultProperties.getProperty(AUTH_TYPE_USER));
> 			authenticated = true;
> 			close(ctx);
> 
> 			if (getLogger().isDebugEnabled()) {
>                  getLogger().debug("Context closed.");
>              }
> 			
>          } catch (NamingException e) {
>              // log this failure
>              // StringWriter writer = new StringWriter();
>              // e.printStackTrace(new PrintWriter(writer));
>              if (getLogger().isInfoEnabled()) {
>                  getLogger().info("Bind for user " + principal + " to  
> Ldap server failed: ", e);
>              }
>          }
> 		
> 		catch(IOException e){
>              // log this failure
>              // StringWriter writer = new StringWriter();
>              // e.printStackTrace(new PrintWriter(writer));
>             if (getLogger().isInfoEnabled()) {
>                  getLogger().info("Can not read properties from File  
> config/ac/passwd/ldap.properties ", e);
>              }
>          }
>          return authenticated;
>      }
> 
>      /**
>       * @see org.apache.lenya.ac.Item#getName()
>       */
>      public String getName() {
>          return ldapName;
>      }
> 
>      /**
>       * LDAP Users fetch their name information from the LDAP server, so  
> we don't store it locally.
>       * Since we only have read access we basically can't set the name,  
> i.e. any request to change
>       * the name is ignored.
>       *
>       * @param string is ignored
>       */
>      public void setName(String string) {
>          // we do not have write access to LDAP, so we ignore
>          // change request to the name.
>      }
> 
>      /**
>       * The LDAPUser doesn't store any passwords as they are handled by  
> LDAP
>       *
>       * @param plainTextPassword is ignored
>       */
>      public void setPassword(String plainTextPassword) {
>          setEncryptedPassword(null);
>      }
> 
>      /**
>       * The LDAPUser doesn't store any passwords as they are handled by  
> LDAP
>       *
>       * @param encryptedPassword is ignored
>       */
>      protected void setEncryptedPassword(String encryptedPassword) {
>          encryptedPassword = null;
>      }
> 	
> 	
>      /**
>       * Connect to the LDAP server
>       *
>       * @param principal the principal string for the LDAP connection
>       * @param credentials the credentials for the LDAP connection
>       * @return a <code>LdapContext</code>
>       * @throws NamingException if there are problems establishing the  
> Ldap connection
>       */
>      private LdapContext bind(String principal, String credentials)  
> throws NamingException {
> 		return this.bind(principal, credentials,  
> defaultProperties.getProperty(SECURITY_AUTHENTICATION));
> 		}
> 	
> 
>      /**
>       * Connect to the LDAP server
>       *
>       * @param principal the principal string for the LDAP connection
>       * @param credentials the credentials for the LDAP connection
>       * @param authMethod Authentication Method (simple or none)
>       * @return a <code>LdapContext</code>
>       * @throws NamingException if there are problems establishing the  
> Ldap connection
>       */
>      private LdapContext bind(String principal, String credentials,  
> String authMethod ) throws NamingException {
> 
>         getLogger().info("Binding principal: [" + principal + "]");
> 
>          Hashtable env = new Hashtable();
> 
>          System.setProperty("javax.net.ssl.trustStore",  
> getConfigurationDirectory()
>                  .getAbsolutePath()
>                  + File.separator +  
> defaultProperties.getProperty(KEY_STORE));
> 				
> 				
> 		if(authMethod.equals("none")){
> 			env.put(Context.PROVIDER_URL,  
> defaultProperties.getProperty(PROVIDER_URL) );
> 			env.put(Context.SECURITY_AUTHENTICATION, "none");
> 			env.put(Context.SECURITY_PROTOCOL, "ssl");
> 			 
> env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactor 
> y");
> 		}
> 		else {
> 			env.put(Context.INITIAL_CONTEXT_FACTORY,  
> LdapCtxFactory.class.getName());
> 			env.put(Context.PROVIDER_URL,  
> defaultProperties.getProperty(PROVIDER_URL));
> 			env.put(Context.SECURITY_PROTOCOL,  
> defaultProperties.getProperty(SECURITY_PROTOCOL));
> 			env.put(Context.SECURITY_AUTHENTICATION, authMethod);
> 			env.put(Context.SECURITY_PRINCIPAL, principal);
> 			env.put(Context.SECURITY_CREDENTIALS, credentials);
> 		}
>          LdapContext ctx = new InitialLdapContext(env, null);
> 
>         getLogger().info("Finished binding principal.");
> 
>          return ctx;
>      }
> 
>      /**
>       * Close the connection to the LDAP server
>       *
>       * @param ctx the context that was returned from the bind
>       * @throws NamingException if there is a problem communicating to  
> the LDAP server
>       */
>      private void close(Context ctx) throws NamingException {
>          ctx.close();
>      }
> 
>      /**
>       * Read the properties
>       *
>       * @throws IOException if the properties cannot be found.
>       */
>      private void readProperties() throws IOException {
>          // create and load default properties
>          File propertiesFile = new File(getConfigurationDirectory(),  
> "ldap.properties");
> 
>          if (defaultProperties == null) {
>              defaultProperties = new Properties();
> 
>              FileInputStream in = null;
>              try {
>                  in = new FileInputStream(propertiesFile);
>                  defaultProperties.load(in);
>              } finally {
>                  if (in != null) {
>                      in.close();
>                  }
>              }
>          }
>      }
> 	
>      /**
>       * Search DN in LDAP
>       *
>       * @param user Lenya-Users name
>       * @param bindUser manager-username for simple LDAP connection
>       * @param bindPw manger-password for simple LDAP connection
>       * @return a <code>Lenya-Users LDAP DN</code
>       * @throws NamingException if there are problems establishing the  
> Ldap connection
> 	 */
>      private String searchDN(String user, String bindUser, String  
> bindPw) throws NamingException {
> 				
> 			String principal = new String("");
> 			LdapContext searchCtx = null;
> 			searchCtx= bind(bindUser, bindPw);
> 
> 			// Set Scope
> 			SearchControls scope = new SearchControls();
> 			scope.setSearchScope(SearchControls.SUBTREE_SCOPE);
> 
> 			NamingEnumeration results =  
> searchCtx.search(defaultProperties.getProperty(BASE_DN),
> 														"("+defaultProperties.getProperty(USER_ATTR)+"="+user+")",
> 														scope );
> 														
> 			while (results != null && results.hasMore()) {
> 				SearchResult si = (SearchResult) results.next();
> 				principal = si.getName();
> 				if(si.isRelative()) {
> 					if (principal.length()>0) principal = principal +","+  
> defaultProperties.getProperty(BASE_DN);
> 				}
> 				if (getLogger().isDebugEnabled()) {
> 					getLogger().debug("Authenticating with principal [" + principal +  
> "]");
> 				}
> 			}
> 			close(searchCtx);
> 			return principal;
> 		}
> }
> 
> 
> ----------------------------------------------------------------------
> config/ac/passwd/ldap.properties
> 
> 
> ### LDAP URL
> provider-url=ldaps://ldap.foodomain.com:636/
> 
> ### Normal Authentication #######################
> ### Manager which is allowed to retrieve a list of "all" users  
> (fullname) from LDAP server
> # mgr-dn=cn=proxyauth,ou=People,ou=FooOrg,dc=foodomain,dc=com
> ### Manager Password
> # mgr-pw=sekret
> # security-authentication=simple
> 
> ### Anonymous Authentication ####################
> mgr-dn=anonymous
> mgr-pw=none
> security-authentication=none
> 
> ### Base DN, Lenya-User have to be in this Folder or a Subfolder
> base-dn=dc=foodomain,dc=com
> 
> ### keystore is taken relatively to the publication config/ac directory
> key-store=.keystore
> security-protocol=ssl
> 
> ### Attribute-name of User Partition (Lenya-User)
> usr-attr=uid
> 
> ### Authentication for Lenya-User
> user-authentication=simple
> 
> -- 
> ========================================
> Markus Anwander
> University of Berne
> markus.anwander@id.unibe.ch


---------------------------------------------------------------------
To unsubscribe, e-mail: lenya-user-unsubscribe@cocoon.apache.org
For additional commands, e-mail: lenya-user-help@cocoon.apache.org