CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-security--spring-security-ldap

Spring Security LDAP module providing comprehensive LDAP authentication and authorization capabilities for enterprise applications

Pending
Overview
Eval results
Files

context-management.mddocs/

Context Management

LDAP context source and template classes for managing connections to LDAP servers with support for authentication, connection pooling, and operation execution.

Capabilities

DefaultSpringSecurityContextSource

Spring Security's LDAP context source implementation providing connection management and authentication for LDAP operations.

/**
 * Default LDAP context source implementation for Spring Security providing connection management
 * and authentication support for LDAP directory operations
 */
public class DefaultSpringSecurityContextSource implements InitializingBean, DisposableBean {
    /**
     * Creates an LDAP context source with the specified provider URL
     * @param providerUrl the LDAP URL (e.g., "ldap://localhost:389/dc=springframework,dc=org")
     */
    public DefaultSpringSecurityContextSource(String providerUrl);
    
    /**
     * Creates an LDAP context source with provider URL and base DN
     * @param providerUrl the LDAP URL
     * @param baseDn the base distinguished name for operations
     */
    public DefaultSpringSecurityContextSource(String providerUrl, String baseDn);
    
    /**
     * Creates an LDAP context source from a list of URLs for failover support
     * @param urls list of LDAP URLs for failover
     * @param baseDn the base distinguished name
     */
    public DefaultSpringSecurityContextSource(List<String> urls, String baseDn);
    
    /**
     * Sets the distinguished name for the manager user
     * @param userDn the manager user DN (e.g., "cn=manager,dc=springframework,dc=org")
     */
    public void setUserDn(String userDn);
    
    /**
     * Sets the password for the manager user
     * @param password the manager password
     */
    public void setPassword(String password);
    
    /**
     * Gets a read-only LDAP context for search operations
     * @return DirContext for read-only operations
     * @throws NamingException if context creation fails
     */
    public DirContext getReadOnlyContext() throws NamingException;
    
    /**
     * Gets a read-write LDAP context for modification operations
     * @return DirContext for read-write operations
     * @throws NamingException if context creation fails
     */
    public DirContext getReadWriteContext() throws NamingException;
    
    /**
     * Gets an authenticated context using the provided credentials
     * @param principal the authentication principal (username or DN)
     * @param credentials the authentication credentials (password)
     * @return DirContext authenticated with provided credentials
     * @throws NamingException if authentication fails
     */
    public DirContext getContext(String principal, String credentials) throws NamingException;
    
    /**
     * Sets the LDAP connection pool configuration
     * @param pooled true to enable connection pooling
     */
    public void setPooled(boolean pooled);
    
    /**
     * Sets the referral handling strategy
     * @param referral the referral strategy ("follow", "ignore", or "throw")
     */
    public void setReferral(String referral);
    
    /**
     * Sets additional LDAP environment properties
     * @param baseEnvironmentProperties map of LDAP environment properties
     */
    public void setBaseEnvironmentProperties(Map<String, Object> baseEnvironmentProperties);
}

Usage Examples:

// Basic context source configuration
DefaultSpringSecurityContextSource contextSource = 
    new DefaultSpringSecurityContextSource("ldap://localhost:389/dc=springframework,dc=org");
contextSource.setUserDn("cn=manager,dc=springframework,dc=org");
contextSource.setPassword("password");
contextSource.afterPropertiesSet();

// Failover configuration with multiple URLs
List<String> urls = Arrays.asList(
    "ldap://ldap1.example.com:389",
    "ldap://ldap2.example.com:389"
);
DefaultSpringSecurityContextSource contextSource = 
    new DefaultSpringSecurityContextSource(urls, "dc=example,dc=com");

// With connection pooling and referral handling
contextSource.setPooled(true);
contextSource.setReferral("follow");

// Custom environment properties
Map<String, Object> env = new HashMap<>();
env.put("java.naming.ldap.connect.timeout", "5000");
env.put("java.naming.ldap.read.timeout", "10000");
contextSource.setBaseEnvironmentProperties(env);

SpringSecurityLdapTemplate

LDAP template class providing high-level operations for common LDAP tasks with Spring Security integration.

/**
 * LDAP template class providing simplified LDAP operations with Spring Security integration
 */
public class SpringSecurityLdapTemplate {
    /**
     * Creates an LDAP template with the specified context source
     * @param contextSource the LDAP context source
     */
    public SpringSecurityLdapTemplate(ContextSource contextSource);
    
    /**
     * Searches for a single entry matching the specified criteria
     * @param base the base DN for the search
     * @param filter the LDAP search filter
     * @param params parameters to substitute in the filter
     * @return DirContextOperations representing the found entry
     * @throws IncorrectResultSizeDataAccessException if multiple entries found
     */
    public DirContextOperations searchForSingleEntry(String base, String filter, Object[] params);
    
    /**
     * Searches for a context matching the specified criteria
     * @param base the base DN for the search
     * @param filter the LDAP search filter
     * @param params parameters to substitute in the filter
     * @return DirContextOperations representing the found context
     */
    public DirContextOperations searchForContext(String base, String filter, Object[] params);
    
    /**
     * Searches for all entries matching the specified criteria
     * @param base the base DN for the search
     * @param filter the LDAP search filter
     * @param params parameters to substitute in the filter
     * @param mapper mapper for converting search results
     * @return set of mapped results
     */
    public <T> Set<T> searchForSingleAttributeValues(String base, String filter, Object[] params, 
        String attributeName);
    
    /**
     * Performs authentication by attempting to bind with provided credentials
     * @param base the base DN for the search
     * @param filter the LDAP search filter to find the user
     * @param params parameters to substitute in the filter
     * @param password the password to authenticate with
     * @return true if authentication successful
     */
    public boolean authenticate(String base, String filter, Object[] params, String password);
    
    /**
     * Compares an attribute value against the stored value in LDAP
     * @param dn the distinguished name of the entry
     * @param attributeName the attribute to compare
     * @param value the value to compare against
     * @return true if values match
     */
    public boolean compare(String dn, String attributeName, Object value);
    
    /**
     * Modifies LDAP entry attributes
     * @param dn the distinguished name of the entry to modify
     * @param mods array of modification items
     */
    public void modifyAttributes(String dn, ModificationItem[] mods);
    
    /**
     * Sets the search controls for LDAP operations
     * @param searchControls the search controls to use
     */
    public void setSearchControls(SearchControls searchControls);
    
    /**
     * Sets whether to ignore size limits during searches
     * @param ignoreSizeLimitExceededExceptions true to ignore size limit exceptions
     */
    public void setIgnorePartialResultException(boolean ignoreSizeLimitExceededExceptions);
}

Usage Examples:

// Basic template usage
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);

// Search for single user
DirContextOperations user = template.searchForSingleEntry(
    "ou=people", "uid={0}", new Object[]{"johndoe"});

// Authenticate user
boolean authenticated = template.authenticate(
    "ou=people", "uid={0}", new Object[]{"johndoe"}, "password");

// Search for attribute values
Set<String> emails = template.searchForSingleAttributeValues(
    "ou=people", "department={0}", new Object[]{"IT"}, "mail");

// Compare attribute value
boolean isActive = template.compare("uid=johndoe,ou=people", "active", "true");

LdapUtils

Utility class providing static helper methods for common LDAP operations and DN manipulation.

/**
 * Utility class providing static helper methods for LDAP operations and DN manipulation
 */
public final class LdapUtils {
    /**
     * Extracts the relative DN from a full DN given a base DN
     * @param baseDn the base distinguished name
     * @param fullDn the full distinguished name
     * @return the relative DN as a string
     */
    public static String getRelativeName(String baseDn, String fullDn);
    
    /**
     * Builds a full DN from a relative DN and base DN
     * @param dn the relative DN
     * @param baseDn the base DN
     * @return LdapName representing the full DN
     */
    public static LdapName getFullDn(LdapName dn, Name baseDn);
    
    /**
     * Converts a NamingException to a Spring DataAccessException
     * @param e the NamingException to convert
     * @return DataAccessException wrapping the original exception
     */
    public static DataAccessException convertLdapException(NamingException e);
    
    /**
     * Creates a new DN by adding an RDN to an existing DN
     * @param dn the existing DN
     * @param rdn the RDN to add
     * @return new LdapName with the added RDN
     */
    public static LdapName newLdapName(String dn);
    
    /**
     * Removes the first RDN from a DN
     * @param dn the DN to modify
     * @return new LdapName with first RDN removed
     */
    public static LdapName removeFirst(LdapName dn);
    
    /**
     * Gets the first RDN from a DN
     * @param dn the DN to examine
     * @return the first RDN as a string
     */
    public static String getFirstRdn(LdapName dn);
}

Username to DN Mapping

Strategy interface and implementation for converting usernames to LDAP Distinguished Names.

/**
 * Strategy interface for mapping usernames to Distinguished Names
 */
public interface LdapUsernameToDnMapper {
    /**
     * Builds an LDAP Distinguished Name from a username
     * @param username the username to map
     * @return LdapName representing the user's DN
     */
    LdapName buildLdapName(String username);
    
    /**
     * Builds a Distinguished Name from a username (deprecated)
     * @param username the username to map
     * @return DistinguishedName representing the user's DN
     * @deprecated Use buildLdapName(String) instead
     */
    @Deprecated
    DistinguishedName buildDn(String username);
}

/**
 * Default implementation that appends a name component to the userDnBase context
 * using the usernameAttributeName property
 */
public class DefaultLdapUsernameToDnMapper implements LdapUsernameToDnMapper {
    /**
     * Creates a default username to DN mapper
     * @param userDnBase the base name of the DN
     * @param usernameAttribute the attribute to append for the username component
     */
    public DefaultLdapUsernameToDnMapper(String userDnBase, String usernameAttribute);
    
    /**
     * Builds an LDAP name from the username by appending it to the base DN
     * @param username the username to map
     * @return LdapName representing the user's full DN
     */
    public LdapName buildLdapName(String username);
}

Configuration Examples

Basic Context Source Configuration

@Configuration
@EnableWebSecurity
public class LdapContextConfig {
    
    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        DefaultSpringSecurityContextSource contextSource = 
            new DefaultSpringSecurityContextSource("ldap://localhost:389/dc=springframework,dc=org");
        
        // Manager authentication
        contextSource.setUserDn("cn=manager,dc=springframework,dc=org");
        contextSource.setPassword("password");
        
        // Connection settings
        contextSource.setPooled(true);
        contextSource.setReferral("follow");
        
        // Custom environment properties
        Map<String, Object> baseEnv = new HashMap<>();
        baseEnv.put("java.naming.ldap.connect.timeout", "5000");
        baseEnv.put("java.naming.ldap.read.timeout", "10000");
        baseEnv.put("java.naming.security.protocol", "ssl");
        contextSource.setBaseEnvironmentProperties(baseEnv);
        
        return contextSource;
    }
    
    @Bean
    public SpringSecurityLdapTemplate ldapTemplate() {
        SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource());
        
        // Configure search controls
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setTimeLimit(5000);
        template.setSearchControls(searchControls);
        
        template.setIgnorePartialResultException(true);
        return template;
    }
}

SSL/TLS Configuration

@Bean
public DefaultSpringSecurityContextSource secureContextSource() {
    DefaultSpringSecurityContextSource contextSource = 
        new DefaultSpringSecurityContextSource("ldaps://ldap.example.com:636/dc=example,dc=com");
    
    contextSource.setUserDn("cn=admin,dc=example,dc=com");
    contextSource.setPassword("adminPassword");
    
    // SSL/TLS configuration
    Map<String, Object> baseEnv = new HashMap<>();
    baseEnv.put("java.naming.security.protocol", "ssl");
    baseEnv.put("java.naming.ldap.factory.socket", "javax.net.ssl.SSLSocketFactory");
    
    // Trust store configuration (if needed)
    baseEnv.put("javax.net.ssl.trustStore", "/path/to/truststore.jks");
    baseEnv.put("javax.net.ssl.trustStorePassword", "truststorePassword");
    
    contextSource.setBaseEnvironmentProperties(baseEnv);
    return contextSource;
}

High Availability Configuration

@Bean
public DefaultSpringSecurityContextSource haContextSource() {
    // Multiple LDAP servers for failover
    List<String> urls = Arrays.asList(
        "ldap://ldap1.example.com:389",
        "ldap://ldap2.example.com:389", 
        "ldap://ldap3.example.com:389"
    );
    
    DefaultSpringSecurityContextSource contextSource = 
        new DefaultSpringSecurityContextSource(urls, "dc=example,dc=com");
    
    contextSource.setUserDn("cn=admin,dc=example,dc=com");
    contextSource.setPassword("adminPassword");
    
    // Connection and timeout settings
    Map<String, Object> baseEnv = new HashMap<>();
    baseEnv.put("java.naming.ldap.connect.timeout", "3000");
    baseEnv.put("java.naming.ldap.read.timeout", "5000");
    baseEnv.put("com.sun.jndi.ldap.connect.pool", "true");
    baseEnv.put("com.sun.jndi.ldap.connect.pool.maxsize", "10");
    baseEnv.put("com.sun.jndi.ldap.connect.pool.prefsize", "5");
    
    contextSource.setBaseEnvironmentProperties(baseEnv);
    return contextSource;
}

Custom Template Operations

@Service
public class CustomLdapService {
    
    private final SpringSecurityLdapTemplate ldapTemplate;
    
    public CustomLdapService(SpringSecurityLdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public List<String> findUsersByDepartment(String department) {
        return ldapTemplate.searchForSingleAttributeValues(
            "ou=people", 
            "department={0}", 
            new Object[]{department}, 
            "uid"
        ).stream().collect(Collectors.toList());
    }
    
    public boolean validateUserCredentials(String username, String password) {
        return ldapTemplate.authenticate(
            "ou=people", 
            "uid={0}", 
            new Object[]{username}, 
            password
        );
    }
    
    public void updateUserEmail(String username, String newEmail) {
        String userDn = findUserDn(username);
        ModificationItem[] mods = new ModificationItem[] {
            new ModificationItem(DirContext.REPLACE_ATTRIBUTE, 
                new BasicAttribute("mail", newEmail))
        };
        ldapTemplate.modifyAttributes(userDn, mods);
    }
    
    private String findUserDn(String username) {
        DirContextOperations user = ldapTemplate.searchForSingleEntry(
            "ou=people", "uid={0}", new Object[]{username});
        return user.getDn().toString();
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework-security--spring-security-ldap

docs

authentication.md

authorities.md

context-management.md

embedded-server.md

index.md

json-serialization.md

password-policy.md

user-details.md

tile.json