Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright 1999-2002,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.catalina.realm;
  
  
  import java.util.List;
  
  import javax.naming.Name;
  import  org.apache.catalina.LifecycleException;
  import  org.apache.catalina.util.Base64;


Implementation of Realm that works with a directory server accessed via the Java Naming and Directory Interface (JNDI) APIs. The following constraints are imposed on the data structure in the underlying directory server:

  • Each user that can be authenticated is represented by an individual element in the top level DirContext that is accessed via the connectionURL property.
  • If a socket connection can not be made to the connectURL an attempt will be made to use the alternateURL if it exists.
  • Each user element has a distinguished name that can be formed by substituting the presented username into a pattern configured by the userPattern property.
  • Alternatively, if the userPattern property is not specified, a unique element can be located by searching the directory context. In this case:
    • The userSearch pattern specifies the search filter after substitution of the username.
    • The userBase property can be set to the element that is the base of the subtree containing users. If not specified, the search base is the top-level context.
    • The userSubtree property can be set to true if you wish to search the entire subtree of the directory context. The default value of false requests a search of only the current level.
  • The user may be authenticated by binding to the directory with the username and password presented. This method is used when the userPassword property is not specified.
  • The user may be authenticated by retrieving the value of an attribute from the directory and comparing it explicitly with the value presented by the user. This method is used when the userPassword property is specified, in which case:
    • The element for this user must contain an attribute named by the userPassword property.
    • The value of the user password attribute is either a cleartext String, or the result of passing a cleartext String through the RealmBase.digest() method (using the standard digest support included in RealmBase).
    • The user is considered to be authenticated if the presented credentials (after being passed through RealmBase.digest()) are equal to the retrieved value for the user password attribute.
  • Each group of users that has been assigned a particular role may be represented by an individual element in the top level DirContext that is accessed via the connectionURL property. This element has the following characteristics:
    • The set of all possible groups of interest can be selected by a search pattern configured by the roleSearch property.
    • The roleSearch pattern optionally includes pattern replacements "{0}" for the distinguished name, and/or "{1}" for the username, of the authenticated user for which roles will be retrieved.
    • The roleBase property can be set to the element that is the base of the search for matching roles. If not specified, the entire context will be searched.
    • The roleSubtree property can be set to true if you wish to search the entire subtree of the directory context. The default value of false requests a search of only the current level.
    • The element includes an attribute (whose name is configured by the roleName property) containing the name of the role represented by this element.
  • In addition, roles may be represented by the values of an attribute in the user's element whose name is configured by the userRoleName property.
  • Note that the standard <security-role-ref> element in the web application deployment descriptor allows applications to refer to roles programmatically by names other than those used in the directory server itself.

TODO - Support connection pooling (including message format objects) so that authenticate() does not have to be synchronized.

WARNING - There is a reported bug against the Netscape provider code (com.netscape.jndi.ldap.LdapContextFactory) with respect to successfully authenticated a non-existing user. The report is here: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=11210 . With luck, Netscape has updated their provider code and this is not an issue.

Author(s):
John Holman
Craig R. McClanahan
Version:
$Revision: 1.15 $ $Date: 2004/10/10 20:43:49 $
 
 
 public class JNDIRealm extends RealmBase {
 
 
     // ----------------------------------------------------- Instance Variables
 
    
The type of authentication to use
 
     protected String authentication = null;

    
The connection username for the server we will contact.
 
     protected String connectionName = null;


    
The connection password for the server we will contact.
 
     protected String connectionPassword = null;


    
The connection URL for the server we will contact.
 
     protected String connectionURL = null;


    
The directory context linking us to our directory server.
 
     protected DirContext context = null;


    
The JNDI context factory used to acquire our InitialContext. By default, assumes use of an LDAP server using the standard JNDI LDAP provider.
 
     protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

    
    
How aliases should be dereferenced during search operations.
 
     protected String derefAliases = null;

    
Constant that holds the name of the environment property for specifying the manner in which aliases should be dereferenced.
 
     public final static String DEREF_ALIASES = "java.naming.ldap.derefAliases";

    
Descriptive information about this Realm implementation.
 
     protected static final String info =
         "org.apache.catalina.realm.JNDIRealm/1.0";


    
Descriptive information about this Realm implementation.
 
     protected static final String name = "JNDIRealm";


    
The protocol that will be used in the communication with the directory server.
 
     protected String protocol = null;


    
How should we handle referrals? Microsoft Active Directory can't handle the default case, so an application authenticating against AD must set referrals to "follow".
 
     protected String referrals = null;


    
The base element for user searches.
 
     protected String userBase = "";


    
The message format used to search for a user, with "{0}" marking the spot where the username goes.
 
     protected String userSearch = null;


    
The MessageFormat object associated with the current userSearch.
 
     protected MessageFormat userSearchFormat = null;


    
Should we search the entire subtree for matching users?
 
     protected boolean userSubtree = false;


    
The attribute name used to retrieve the user password.
 
     protected String userPassword = null;


    
A string of LDAP user patterns or paths, ":"-separated These will be used to form the distinguished name of a user, with "{0}" marking the spot where the specified username goes. This is similar to userPattern, but allows for multiple searches for a user.
 
     protected String[] userPatternArray = null;


    
The message format used to form the distinguished name of a user, with "{0}" marking the spot where the specified username goes.
 
     protected String userPattern = null;


    
An array of MessageFormat objects associated with the current userPatternArray.
 
     protected MessageFormat[] userPatternFormatArray = null;


    
The base element for role searches.
 
     protected String roleBase = "";


    
The MessageFormat object associated with the current roleSearch.
 
     protected MessageFormat roleFormat = null;


    
The name of an attribute in the user's entry containing roles for that user
 
     protected String userRoleName = null;


    
The name of the attribute containing roles held elsewhere
 
     protected String roleName = null;


    
The message format used to select roles for a user, with "{0}" marking the spot where the distinguished name of the user goes.
 
     protected String roleSearch = null;


    
Should we search the entire subtree for matching memberships?
 
     protected boolean roleSubtree = false;

    
An alternate URL, to which, we should connect if connectionURL fails.
 
     protected String alternateURL;

    
The number of connection attempts. If greater than zero we use the alternate url.
 
     protected int connectionAttempt = 0;

    
The current user pattern to be used for lookup and binding of a user.
 
     protected int curUserPattern = 0;
 
     // ------------------------------------------------------------- Properties
 
    
Return the type of authentication to use.
 
     public String getAuthentication() {
 
         return ;
 
     }

    
Set the type of authentication to use.

Parameters:
authentication The authentication
 
     public void setAuthentication(String authentication) {
 
         this. = authentication;
 
     }

    
Return the connection username for this Realm.
 
     public String getConnectionName() {
 
         return (this.);
 
     }


    
Set the connection username for this Realm.

Parameters:
connectionName The new connection username
 
     public void setConnectionName(String connectionName) {
 
         this. = connectionName;
 
     }


    
Return the connection password for this Realm.
 
     public String getConnectionPassword() {
 
         return (this.);
 
     }


    
Set the connection password for this Realm.

Parameters:
connectionPassword The new connection password
 
     public void setConnectionPassword(String connectionPassword) {
 
         this. = connectionPassword;
 
     }


    
Return the connection URL for this Realm.
 
     public String getConnectionURL() {
 
         return (this.);
 
     }


    
Set the connection URL for this Realm.

Parameters:
connectionURL The new connection URL
 
     public void setConnectionURL(String connectionURL) {
 
         this. = connectionURL;
 
     }


    
Return the JNDI context factory for this Realm.
 
     public String getContextFactory() {
 
         return (this.);
 
     }


    
Set the JNDI context factory for this Realm.

Parameters:
contextFactory The new context factory
 
     public void setContextFactory(String contextFactory) {
 
         this. = contextFactory;
 
     }

    
Return the derefAliases setting to be used.
 
     public java.lang.String getDerefAliases() {
         return ;
     }  
    
    
Set the value for derefAliases to be used when searching the directory.

Parameters:
derefAliases New value of property derefAliases.
 
     public void setDerefAliases(java.lang.String derefAliases) {
       this. = derefAliases;
     }

    
Return the protocol to be used.
 
     public String getProtocol() {
 
         return ;
 
     }

    
Set the protocol for this Realm.

Parameters:
protocol The new protocol.
 
     public void setProtocol(String protocol) {
 
         this. = protocol;
 
     }


    
Returns the current settings for handling JNDI referrals.
 
     public String getReferrals () {
         return ;
     }


    
How do we handle JNDI referrals? ignore, follow, or throw (see javax.naming.Context.REFERRAL for more information).
 
     public void setReferrals (String referrals) {
         this. = referrals;
     }


    
Return the base element for user searches.
 
     public String getUserBase() {
 
         return (this.);
 
     }


    
Set the base element for user searches.

Parameters:
userBase The new base element
 
     public void setUserBase(String userBase) {
 
         this. = userBase;
 
     }


    
Return the message format pattern for selecting users in this Realm.
 
     public String getUserSearch() {
 
         return (this.);
 
     }


    
Set the message format pattern for selecting users in this Realm.

Parameters:
userSearch The new user search pattern
 
     public void setUserSearch(String userSearch) {
 
         this. = userSearch;
         if (userSearch == null)
              = null;
         else
              = new MessageFormat(userSearch);
 
     }


    
Return the "search subtree for users" flag.
 
     public boolean getUserSubtree() {
 
         return (this.);
 
     }


    
Set the "search subtree for users" flag.

Parameters:
userSubtree The new search flag
 
     public void setUserSubtree(boolean userSubtree) {
 
         this. = userSubtree;
 
     }


    
Return the user role name attribute name for this Realm.
 
     public String getUserRoleName() {
 
         return ;
     }


    
Set the user role name attribute name for this Realm.

Parameters:
userRoleName The new userRole name attribute name
 
     public void setUserRoleName(String userRoleName) {
 
         this. = userRoleName;
 
     }


    
Return the base element for role searches.
 
     public String getRoleBase() {
 
         return (this.);
 
     }


    
Set the base element for role searches.

Parameters:
roleBase The new base element
 
     public void setRoleBase(String roleBase) {
 
         this. = roleBase;
 
     }


    
Return the role name attribute name for this Realm.
 
     public String getRoleName() {
 
         return (this.);
 
     }


    
Set the role name attribute name for this Realm.

Parameters:
roleName The new role name attribute name
 
     public void setRoleName(String roleName) {
 
         this. = roleName;
 
     }


    
Return the message format pattern for selecting roles in this Realm.
 
     public String getRoleSearch() {
 
         return (this.);
 
     }


    
Set the message format pattern for selecting roles in this Realm.

Parameters:
roleSearch The new role search pattern
 
     public void setRoleSearch(String roleSearch) {
 
         this. = roleSearch;
         if (roleSearch == null)
              = null;
         else
              = new MessageFormat(roleSearch);
 
     }


    
Return the "search subtree for roles" flag.
 
     public boolean getRoleSubtree() {
 
         return (this.);
 
     }


    
Set the "search subtree for roles" flag.

Parameters:
roleSubtree The new search flag
 
     public void setRoleSubtree(boolean roleSubtree) {
 
         this. = roleSubtree;
 
     }


    
Return the password attribute used to retrieve the user password.
 
     public String getUserPassword() {
 
         return (this.);
 
     }


    
Set the password attribute used to retrieve the user password.

Parameters:
userPassword The new password attribute
 
     public void setUserPassword(String userPassword) {
 
         this. = userPassword;
 
     }


    
Return the message format pattern for selecting users in this Realm.
 
     public String getUserPattern() {
 
         return (this.);
 
     }


    
Set the message format pattern for selecting users in this Realm. This may be one simple pattern, or multiple patterns to be tried, separated by parentheses. (for example, either "cn={0}", or "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported, but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is also valid. Complex search strings with &, etc are NOT supported.

Parameters:
userPattern The new user pattern
 
     public void setUserPattern(String userPattern) {
 
         this. = userPattern;
         if (userPattern == null)
              = null;
         else {
              = parseUserPatternString(userPattern);
             int len = this..length;
              = new MessageFormat[len];
             for (int i=0; i < leni++) {
                 [i] =
                     new MessageFormat([i]);
             }
         }
     }


    
Getter for property alternateURL.

Returns:
Value of property alternateURL.
 
     public String getAlternateURL() {
 
         return this.;
 
     }


    
Setter for property alternateURL.

Parameters:
alternateURL New value of property alternateURL.
 
     public void setAlternateURL(String alternateURL) {
 
         this. = alternateURL;
 
     }
 
 
     // ---------------------------------------------------------- Realm Methods
 

    
Return the Principal associated with the specified username and credentials, if there is one; otherwise return null. If there are any errors with the JDBC connection, executing the query or anything we return null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent request will automatically re-open it.

Parameters:
username Username of the Principal to look up
credentials Password or other credentials to use in authenticating this username
 
     public Principal authenticate(String usernameString credentials) {
 
         DirContext context = null;
         Principal principal = null;
 
         try {
 
             // Ensure that we have a directory context available
             context = open();
 
             // Occassionally the directory context will timeout.  Try one more
             // time before giving up.
             try {
 
                 // Authenticate the specified username if possible
                 principal = authenticate(contextusernamecredentials);
 
             } catch (CommunicationException e) {
 
 
                 // If contains the work closed. Then assume socket is closed.
                 // If message is null, assume the worst and allow the
                 // connection to be closed.
                 if (e.getMessage()!=null &&
                     e.getMessage().indexOf("closed") < 0)
                     throw(e);
 
                 // log the exception so we know it's there.
                 container.getLogger().error(sm.getString("jndiRealm.exception"), e);
 
                 // close the connection so we know it will be reopened.
                 if (context != null)
                     close(context);
 
                 // open a new directory context.
                 context = open();
 
                 // Try the authentication again.
                 principal = authenticate(contextusernamecredentials);
 
             }
 
 
             // Release this context
             release(context);
 
             // Return the authenticated Principal (if any)
             return (principal);
 
         } catch (NamingException e) {
 
             // Log the problem for posterity
             container.getLogger().error(sm.getString("jndiRealm.exception"), e);
 
             // Close the connection so that it gets reopened next time
             if (context != null)
                 close(context);
 
             // Return "not authenticated" for this request
             return (null);
 
         }
 
     }
 
 
     // -------------------------------------------------------- Package Methods
 
 
     // ------------------------------------------------------ Protected Methods
 

    
Return the Principal associated with the specified username and credentials, if there is one; otherwise return null.

Parameters:
context The directory context
username Username of the Principal to look up
credentials Password or other credentials to use in authenticating this username
Throws:
NamingException if a directory server error occurs
 
     public synchronized Principal authenticate(DirContext context,
                                                String username,
                                                String credentials)
         throws NamingException {
 
         if (username == null || username.equals("")
             || credentials == null || credentials.equals(""))
             return (null);
 
         if ( != null) {
             for ( = 0;
                   < .;
                  ++) {
                 // Retrieve user information
                 User user = getUser(contextusername);
                 if (user != null) {
                     try {
                         // Check the user's credentials
                         if (checkCredentials(contextusercredentials)) {
                             // Search for additional roles
                             List roles = getRoles(contextuser);
                             return (new GenericPrincipal(this,
                                                          username,
                                                          credentials,
                                                          roles));
                         }
                     } catch (InvalidNameException ine) {
                         // Log the problem for posterity
                         container.getLogger().warn(sm.getString("jndiRealm.exception"), ine);
                         // ignore; this is probably due to a name not fitting
                         // the search path format exactly, as in a fully-
                         // qualified name being munged into a search path
                         // that already contains cn= or vice-versa
                     }
                 }
             }
             return null;
         } else {
             // Retrieve user information
             User user = getUser(contextusername);
             if (user == null)
                 return (null);
 
             // Check the user's credentials
             if (!checkCredentials(contextusercredentials))
                 return (null);
 
             // Search for additional roles
             List roles = getRoles(contextuser);
 
             // Create and return a suitable Principal for this user
             return (new GenericPrincipal(thisusernamecredentialsroles));
         }
     }


    
Return a User object containing information about the user with the specified username, if found in the directory; otherwise return null. If the userPassword configuration attribute is specified, the value of that attribute is retrieved from the user's directory entry. If the userRoleName configuration attribute is specified, all values of that attribute are retrieved from the directory entry.

Parameters:
context The directory context
username Username to be looked up
Throws:
NamingException if a directory server error occurs
 
     protected User getUser(DirContext contextString username)
         throws NamingException {
 
         User user = null;
 
         // Get attributes to retrieve from user entry
         ArrayList list = new ArrayList();
         if ( != null)
             list.add();
         if ( != null)
             list.add();
         String[] attrIds = new String[list.size()];
         list.toArray(attrIds);
 
         // Use pattern or search for user entry
         if ( != null) {
             user = getUserByPattern(contextusernameattrIds);
         } else {
             user = getUserBySearch(contextusernameattrIds);
         }
 
         return user;
     }


    
Use the UserPattern configuration attribute to locate the directory entry for the user with the specified username and return a User object; otherwise return null.

Parameters:
context The directory context
username The username
attrIds String[]containing names of attributes to retrieve.
Throws:
NamingException if a directory server error occurs
 
     protected User getUserByPattern(DirContext context,
                                               String username,
                                               String[] attrIds)
         throws NamingException {
 
         if (username == null || [] == null)
             return (null);
 
         // Form the dn from the user pattern
         String dn = [].format(new String[] { username });
 
         // Return if no attributes to retrieve
         if (attrIds == null || attrIds.length == 0)
             return new User(usernamednnullnull);
        // Get required attributes from user entry
        Attributes attrs = null;
        try {
            attrs = context.getAttributes(dnattrIds);
        } catch (NameNotFoundException e) {
            return (null);
        }
        if (attrs == null)
            return (null);
        // Retrieve value of userPassword
        String password = null;
        if ( != null)
            password = getAttributeValue(attrs);
        // Retrieve values of userRoleName attribute
        ArrayList roles = null;
        if ( != null)
            roles = addAttributeValues(attrsroles);
        return new User(usernamednpasswordroles);
    }


    
Search the directory to return a User object containing information about the user with the specified username, if found in the directory; otherwise return null.

Parameters:
context The directory context
username The username
attrIds String[]containing names of attributes to retrieve.
Throws:
NamingException if a directory server error occurs
    protected User getUserBySearch(DirContext context,
                                           String username,
                                           String[] attrIds)
        throws NamingException {
        if (username == null ||  == null)
            return (null);
        // Form the search filter
        String filter = .format(new String[] { username });
        // Set up the search controls
        SearchControls constraints = new SearchControls();
        if () {
            constraints.setSearchScope(.);
        }
        else {
            constraints.setSearchScope(.);
        }
        // Specify the attributes to be retrieved
        if (attrIds == null)
            attrIds = new String[0];
        constraints.setReturningAttributes(attrIds);
        NamingEnumeration results =
            context.search(filterconstraints);
        // Fail if no entries found
        if (results == null || !results.hasMore()) {
            return (null);
        }
        // Get result for the first entry found
        SearchResult result = (SearchResult)results.next();
        // Check no further entries were found
        if (results.hasMore()) {
            container.getLogger().info("username " + username + " has multiple entries");
            return (null);
        }
        // Get the entry's distinguished name
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse();
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();
        if (container.getLogger().isTraceEnabled())
            container.getLogger().trace("  entry found for " + username + " with dn " + dn);
        // Get the entry's attributes
        Attributes attrs = result.getAttributes();
        if (attrs == null)
            return null;
        // Retrieve value of userPassword
        String password = null;
        if ( != null)
            password = getAttributeValue(attrs);
        // Retrieve values of userRoleName attribute
        ArrayList roles = null;
        if ( != null)
            roles = addAttributeValues(attrsroles);
        return new User(usernamednpasswordroles);
    }


    
Check whether the given User can be authenticated with the given credentials. If the userPassword configuration attribute is specified, the credentials previously retrieved from the directory are compared explicitly with those presented by the user. Otherwise the presented credentials are checked by binding to the directory as the user.

Parameters:
context The directory context
user The User to be authenticated
credentials The credentials presented by the user
Throws:
NamingException if a directory server error occurs
    protected boolean checkCredentials(DirContext context,
                                     User user,
                                     String credentials)
         throws NamingException {
         boolean validated = false;
         if ( == null) {
             validated = bindAsUser(contextusercredentials);
         } else {
             validated = compareCredentials(contextusercredentials);
         }
         if (container.getLogger().isTraceEnabled()) {
             if (validated) {
                 container.getLogger().trace(sm.getString("jndiRealm.authenticateSuccess",
                                  user.username));
             } else {
                 container.getLogger().trace(sm.getString("jndiRealm.authenticateFailure",
                                  user.username));
             }
         }
         return (validated);
     }



    
Check whether the credentials presented by the user match those retrieved from the directory.

Parameters:
context The directory context
info The User to be authenticated
credentials Authentication credentials
Throws:
NamingException if a directory server error occurs
    protected boolean compareCredentials(DirContext context,
                                         User info,
                                         String credentials)
        throws NamingException {
        if (info == null || credentials == null)
            return (false);
        String password = info.password;
        if (password == null)
            return (false);
        // Validate the credentials specified by the user
        if (container.getLogger().isTraceEnabled())
            container.getLogger().trace("  validating credentials");
        boolean validated = false;
        if (hasMessageDigest()) {
            // iPlanet support if the values starts with {SHA1}
            // The string is in a format compatible with Base64.encode not
            // the Hex encoding of the parent class.
            if (password.startsWith("{SHA}")) {
                /* sync since super.digest() does this same thing */
                synchronized (this) {
                    password = password.substring(5);
                    md.reset();
                    md.update(credentials.getBytes());
                    String digestedPassword =
                        new String(Base64.encode(md.digest()));
                    validated = password.equals(digestedPassword);
                }
            } else {
                // Hex hashes should be compared case-insensitive
                validated = (digest(credentials).equalsIgnoreCase(password));
            }
        } else
            validated = (digest(credentials).equals(password));
        return (validated);
    }



    
Check credentials by binding to the directory as the user

Parameters:
context The directory context
user The User to be authenticated
credentials Authentication credentials
Throws:
NamingException if a directory server error occurs
     protected boolean bindAsUser(DirContext context,
                                  User user,
                                  String credentials)
         throws NamingException {
         Attributes attr;
         if (credentials == null || user == null)
             return (false);
         String dn = user.dn;
         if (dn == null)
             return (false);
         // Validate the credentials specified by the user
         if (container.getLogger().isTraceEnabled()) {
             container.getLogger().trace("  validating credentials by binding as the user");
        }
        // Set up security environment to bind as the user
        context.addToEnvironment(.dn);
        context.addToEnvironment(.credentials);
        // Elicit an LDAP bind operation
        boolean validated = false;
        try {
            if (container.getLogger().isTraceEnabled()) {
                container.getLogger().trace("  binding as "  + dn);
            }
            attr = context.getAttributes(""null);
            validated = true;
        }
        catch (AuthenticationException e) {
            if (container.getLogger().isTraceEnabled()) {
                container.getLogger().trace("  bind attempt failed");
            }
        }
        // Restore the original security environment
        if ( != null) {
            context.addToEnvironment(.,
                                     );
        } else {
            context.removeFromEnvironment(.);
        }
        if ( != null) {
            context.addToEnvironment(.,
                                     );
        }
        else {
            context.removeFromEnvironment(.);
        }
        return (validated);
     }


    
Return a List of roles associated with the given User. Any roles present in the user's directory entry are supplemented by a directory search. If no roles are associated with this user, a zero-length List is returned.

Parameters:
context The directory context we are searching
user The User to be checked
Throws:
NamingException if a directory server error occurs
    protected List getRoles(DirContext contextUser user)
        throws NamingException {
        if (user == null)
            return (null);
        String dn = user.dn;
        String username = user.username;
        if (dn == null || username == null)
            return (null);
        if (container.getLogger().isTraceEnabled())
            container.getLogger().trace("  getRoles(" + dn + ")");
        // Start with roles retrieved from the user entry
        ArrayList list = user.roles;
        if (list == null) {
            list = new ArrayList();
        }
        // Are we configured to do role searches?
        if (( == null) || ( == null))
            return (list);
        // Set up parameters for an appropriate search
        String filter = .format(new String[] { doRFC2254Encoding(dn), username });
        SearchControls controls = new SearchControls();
        if ()
            controls.setSearchScope(.);
        else
            controls.setSearchScope(.);
        controls.setReturningAttributes(new String[] {});
        // Perform the configured search and process the results
        NamingEnumeration results =
            context.search(filtercontrols);
        if (results == null)
            return (list);  // Should never happen, but just in case ...
        while (results.hasMore()) {
            SearchResult result = (SearchResultresults.next();
            Attributes attrs = result.getAttributes();
            if (attrs == null)
                continue;
            list = addAttributeValues(attrslist);
        }
        if (container.getLogger().isTraceEnabled()) {
            if (list != null) {
                container.getLogger().trace("  Returning " + list.size() + " roles");
                for (int i=0; i<list.size(); i++)
                    container.getLogger().trace(  "  Found role " + list.get(i));
            } else {
                container.getLogger().trace("  getRoles about to return null ");
            }
        }
        return (list);
    }


    
Return a String representing the value of the specified attribute.

Parameters:
attrId Attribute name
attrs Attributes containing the required value
Throws:
NamingException if a directory server error occurs
    private String getAttributeValue(String attrIdAttributes attrs)
        throws NamingException {
        if (container.getLogger().isTraceEnabled())
            container.getLogger().trace("  retrieving attribute " + attrId);
        if (attrId == null || attrs == null)
            return null;
        Attribute attr = attrs.get(attrId);
        if (attr == null)
            return (null);
        Object value = attr.get();
        if (value == null)
            return (null);
        String valueString = null;
        if (value instanceof byte[])
            valueString = new String((byte[]) value);
        else
            valueString = value.toString();
        return valueString;
    }



    
Add values of a specified attribute to a list

Parameters:
attrId Attribute name
attrs Attributes containing the new values
values ArrayList containing values found so far
Throws:
NamingException if a directory server error occurs
    private ArrayList addAttributeValues(String attrId,
                                         Attributes attrs,
                                         ArrayList values)
        throws NamingException{
        if (container.getLogger().isTraceEnabled())
            container.getLogger().trace("  retrieving values for attribute " + attrId);
        if (attrId == null || attrs == null)
            return values;
        if (values == null)
            values = new ArrayList();
        Attribute attr = attrs.get(attrId);
        if (attr == null)
            return (values);
        NamingEnumeration e = attr.getAll();
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
        return values;
    }


    
Close any open connection to the directory server for this Realm.

Parameters:
context The directory context to be closed
    protected void close(DirContext context) {
        // Do nothing if there is no opened connection
        if (context == null)
            return;
        // Close our opened connection
        try {
            if (container.getLogger().isDebugEnabled())
                container.getLogger().debug("Closing directory context");
            context.close();
        } catch (NamingException e) {
            container.getLogger().error(sm.getString("jndiRealm.close"), e);
        }
        this. = null;
    }


    
Return a short name for this Realm implementation.
    protected String getName() {
        return ();
    }


    
Return the password associated with the given principal's user name.
    protected String getPassword(String username) {
        return (null);
    }


    
Return the Principal associated with the given user name.
    protected Principal getPrincipal(String username) {
        return (null);
    }



    
Open (if necessary) and return a connection to the configured directory server for this Realm.

Throws:
NamingException if a directory server error occurs
    protected DirContext open() throws NamingException {
        // Do nothing if there is a directory server connection already open
        if ( != null)
            return ();
        try {
            // Ensure that we have a directory context available
             = new InitialDirContext(getDirectoryContextEnvironment());
        } catch (Exception e) {
             = 1;
            // log the first exception.
            container.getLogger().warn(sm.getString("jndiRealm.exception"), e);
            // Try connecting to the alternate url.
             = new InitialDirContext(getDirectoryContextEnvironment());
        } finally {
            // reset it in case the connection times out.
            // the primary may come back.
             = 0;
        }
        return ();
    }

    
Create our directory context configuration.

Returns:
java.util.Hashtable the configuration for the directory context.
        Hashtable env = new Hashtable();
        // Configure our directory context environment.
        if (container.getLogger().isDebugEnabled() &&  == 0)
            container.getLogger().debug("Connecting to URL " + );
        else if (container.getLogger().isDebugEnabled() &&  > 0)
            container.getLogger().debug("Connecting to URL " + );
        if ( != null)
            env.put(.);
        if ( != null)
            env.put(.);
        if ( != null &&  == 0)
            env.put(.);
        else if ( != null &&  > 0)
            env.put(.);
        if ( != null)
            env.put(.);
        if ( != null)
            env.put(.);
        if ( != null)
            env.put(.);
        if ( != null)
            env.put(.);
        return env;
    }


    
Release our use of this connection so that it can be recycled.

Parameters:
context The directory context to release
    protected void release(DirContext context) {
        ; // NO-OP since we are not pooling anything
    }
    // ------------------------------------------------------ Lifecycle Methods


    
Prepare for active use of the public methods of this Component.

Throws:
LifecycleException if this component detects a fatal error that prevents it from being started
    public void start() throws LifecycleException {
        // Validate that we can open our connection
        try {
            open();
        } catch (NamingException e) {
            throw new LifecycleException(sm.getString("jndiRealm.open"), e);
        }
        // Perform normal superclass initialization
        super.start();
    }


    
Gracefully shut down active use of the public methods of this Component.

Throws:
LifecycleException if this component detects a fatal error that needs to be reported
    public void stop() throws LifecycleException {
        // Perform normal superclass finalization
        super.stop();
        // Close any open directory server connection
        close(this.);
    }

    
Given a string containing LDAP patterns for user locations (separated by parentheses in a pseudo-LDAP search string format - "(location1)(location2)", returns an array of those paths. Real LDAP search strings are supported as well (though only the "|" "OR" type).

Parameters:
userPatternString - a string LDAP search paths surrounded by parentheses
    protected String[] parseUserPatternString(String userPatternString) {
        if (userPatternString != null) {
            ArrayList pathList = new ArrayList();
            int startParenLoc = userPatternString.indexOf('(');
            if (startParenLoc == -1) {
                // no parens here; return whole thing
                return new String[] {userPatternString};
            }
            int startingPoint = 0;
            while (startParenLoc > -1) {
                int endParenLoc = 0;
                // weed out escaped open parens and parens enclosing the
                // whole statement (in the case of valid LDAP search
                // strings: (|(something)(somethingelse))
                while ( (userPatternString.charAt(startParenLoc + 1) == '|') ||
                        (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\') ) {
                    startParenLoc = userPatternString.indexOf("("startParenLoc+1);
                }
                endParenLoc = userPatternString.indexOf(")"startParenLoc+1);
                // weed out escaped end-parens
                while (userPatternString.charAt(endParenLoc - 1) == '\\') {
                    endParenLoc = userPatternString.indexOf(")"endParenLoc+1);
                }
                String nextPathPart = userPatternString.substring
                    (startParenLoc+1, endParenLoc);
                pathList.add(nextPathPart);
                startingPoint = endParenLoc+1;
                startParenLoc = userPatternString.indexOf('('startingPoint);
            }
            return (String[])pathList.toArray(new String[] {});
        }
        return null;
    }


    
Given an LDAP search string, returns the string with certain characters escaped according to RFC 2254 guidelines. The character mapping is as follows: char -> Replacement --------------------------- * -> \2a ( -> \28 ) -> \29 \ -> \5c \0 -> \00

Parameters:
inString string to escape according to RFC 2254 guidelines
Returns:
String the escaped/encoded result
    protected String doRFC2254Encoding(String inString) {
        StringBuffer buf = new StringBuffer(inString.length());
        for (int i = 0; i < inString.length(); i++) {
            char c = inString.charAt(i);
            switch (c) {
                case '\\':
                    buf.append("\\5c");
                    break;
                case '*':
                    buf.append("\\2a");
                    break;
                case '(':
                    buf.append("\\28");
                    break;
                case ')':
                    buf.append("\\29");
                    break;
                case '\0':
                    buf.append("\\00");
                    break;
                default:
                    buf.append(c);
                    break;
            }
        }
        return buf.toString();
    }
// ------------------------------------------------------ Private Classes
A private class representing a User
class User {
    String username = null;
    String dn = null;
    String password = null;
    ArrayList roles = null;
    User(String usernameString dnString passwordArrayList roles) {
        this. = username;
        this. = dn;
        this. = password;
        this. = roles;
    }