Example usage for org.springframework.security.ldap DefaultSpringSecurityContextSource DefaultSpringSecurityContextSource

List of usage examples for org.springframework.security.ldap DefaultSpringSecurityContextSource DefaultSpringSecurityContextSource

Introduction

In this page you can find the example usage for org.springframework.security.ldap DefaultSpringSecurityContextSource DefaultSpringSecurityContextSource.

Prototype

public DefaultSpringSecurityContextSource(String providerUrl) 

Source Link

Document

Create and initialize an instance which will connect to the supplied LDAP URL.

Usage

From source file:org.apache.atlas.web.security.AtlasADAuthenticationProvider.java

private Authentication getADBindAuthentication(Authentication authentication) {
    try {//from  ww w .j  a  v  a 2  s  .  c o m
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(adURL);
        ldapContextSource.setUserDn(adBindDN);
        ldapContextSource.setPassword(adBindPassword);
        ldapContextSource.setReferral(adReferral);
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        if (adUserSearchFilter == null || adUserSearchFilter.trim().isEmpty()) {
            adUserSearchFilter = "(sAMAccountName={0})";
        }
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adBase, adUserSearchFilter,
                ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        bindAuthenticator.afterPropertiesSet();

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(
                bindAuthenticator);

        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);
            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            LOG.error("AD Authentication Failed userName or userPassword is null or empty");
            return null;
        }
    } catch (Exception e) {
        LOG.error("AD Authentication Failed:", e);
        return null;
    }
}

From source file:org.apache.atlas.web.security.AtlasLdapAuthenticationProvider.java

private Authentication getLdapAuthentication(Authentication authentication) {

    if (isDebugEnabled) {
        LOG.debug("==> AtlasLdapAuthenticationProvider getLdapAuthentication");
    }//www  .  j  a v  a  2 s  . c o  m

    try {
        // taking the user-name and password from the authentication
        // object.
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        // populating LDAP context source with LDAP URL and user-DN-pattern
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapURL);

        ldapContextSource.setCacheEnvironmentProperties(false);
        ldapContextSource.setAnonymousReadOnly(true);

        // Creating BindAuthenticator using Ldap Context Source.
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern };
        String[] userDnPatterns = ldapUserDNPattern.split(";");
        bindAuthenticator.setUserDnPatterns(userDnPatterns);

        LdapAuthenticationProvider ldapAuthenticationProvider = null;

        if (!StringUtils.isEmpty(ldapGroupSearchBase) && !StringUtils.isEmpty(ldapGroupSearchFilter)) {
            // Creating LDAP authorities populator using Ldap context source and
            // Ldap group search base.
            // populating LDAP authorities populator with group search
            // base,group role attribute, group search filter.
            DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
                    ldapContextSource, ldapGroupSearchBase);
            defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(ldapGroupRoleAttribute);
            defaultLdapAuthoritiesPopulator.setGroupSearchFilter(ldapGroupSearchFilter);
            defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);

            // Creating Ldap authentication provider using BindAuthenticator and Ldap authentication populator
            ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator,
                    defaultLdapAuthoritiesPopulator);
        } else {
            ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);
        }

        // getting user authenticated
        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);

            final UserDetails principal = new User(userName, userPassword, grantedAuths);

            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);

            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            return authentication;
        }
    } catch (Exception e) {
        LOG.error("getLdapAuthentication LDAP Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasLdapAuthenticationProvider getLdapAuthentication");
    }
    return authentication;
}

From source file:org.apache.atlas.web.security.AtlasLdapAuthenticationProvider.java

private LdapContextSource getLdapContextSource() throws Exception {
    LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapURL);
    ldapContextSource.setUserDn(ldapBindDN);
    ldapContextSource.setPassword(ldapBindPassword);
    ldapContextSource.setReferral(ldapReferral);
    ldapContextSource.setCacheEnvironmentProperties(false);
    ldapContextSource.setAnonymousReadOnly(false);
    ldapContextSource.setPooled(true);//from  w  w w .j  a v  a2  s.  c o  m
    ldapContextSource.afterPropertiesSet();
    return ldapContextSource;
}

From source file:org.artifactory.security.ldap.ArtifactoryLdapAuthenticator.java

static LdapContextSource createSecurityContext(LdapSetting ldapSetting) {
    String url = ldapSetting.getLdapUrl();
    String scheme = getLdapScheme(url);
    String baseUrl = getLdapBaseUrl(scheme, url);
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(scheme + baseUrl);
    contextSource.setBase(adjustBase(url.substring((scheme + baseUrl).length())));

    // set default connection timeout, read timeout and referral strategy.
    Map<String, Object> env = new HashMap<>();
    String connectTimeout = ArtifactoryHome.get().getArtifactoryProperties()
            .getProperty("artifactory.security.ldap.connect.timeoutMillis", "10000");
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    String readTimeout = ArtifactoryHome.get().getArtifactoryProperties()
            .getProperty("artifactory.security.ldap.socket.timeoutMillis", "15000");
    env.put("com.sun.jndi.ldap.read.timeout", readTimeout);
    String referralStrategy = ArtifactoryHome.get().getArtifactoryProperties()
            .getProperty("artifactory.security.ldap.referralStrategy", "follow");
    env.put(Context.REFERRAL, referralStrategy);
    String poolIdleTimeout = ArtifactoryHome.get().getArtifactoryProperties()
            .getProperty("artifactory.security.ldap.pool.timeoutMillis", null);
    if (poolIdleTimeout != null) {
        env.put("com.sun.jndi.ldap.connect.pool.timeout", poolIdleTimeout);
    }//  w  w  w .ja  va 2s . com

    contextSource.setBaseEnvironmentProperties(env);
    SearchPattern searchPattern = ldapSetting.getSearch();
    if (searchPattern != null) {
        if (PathUtils.hasText(searchPattern.getManagerDn())) {
            contextSource.setUserDn(searchPattern.getManagerDn());
            contextSource.setPassword(CryptoHelper.decryptIfNeeded(searchPattern.getManagerPassword()));
        } else {
            contextSource.setAnonymousReadOnly(true);
        }
    }

    try {
        contextSource.afterPropertiesSet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return contextSource;
}

From source file:org.opencastproject.userdirectory.ldap.LdapUserProviderInstance.java

/**
 * Constructs an ldap user provider with the needed settings.
 * //from w  w w  .  j  a v  a 2s  .com
 * @param pid
 *          the pid of this service
 * @param organization
 *          the organization
 * @param searchBase
 *          the ldap search base
 * @param searchFilter
 *          the ldap search filter
 * @param url
 *          the url of the ldap server
 * @param userDn
 *          the user to authenticate as
 * @param password
 *          the user credentials
 * @param roleAttributesGlob
 *          the comma separate list of ldap attributes to treat as roles
 * @param cacheSize
 *          the number of users to cache
 * @param cacheExpiration
 *          the number of minutes to cache users
 */
// CHECKSTYLE:OFF
LdapUserProviderInstance(String pid, String organization, String searchBase, String searchFilter, String url,
        String userDn, String password, String roleAttributesGlob, int cacheSize, int cacheExpiration) {
    // CHECKSTYLE:ON
    this.organization = organization;
    logger.debug("Creating LdapUserProvider instance with pid=" + pid + ", and organization=" + organization
            + ", to LDAP server at url:  " + url);

    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(url);
    if (StringUtils.isNotBlank(userDn)) {
        contextSource.setPassword(password);
        contextSource.setUserDn(userDn);
        // Required so that authentication will actually be used
        contextSource.setAnonymousReadOnly(false);
    } else {
        // No password set so try to connect anonymously. 
        contextSource.setAnonymousReadOnly(true);
    }

    try {
        contextSource.afterPropertiesSet();
    } catch (Exception e) {
        throw new org.opencastproject.util.ConfigurationException("Unable to create a spring context source",
                e);
    }
    FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(searchBase, searchFilter,
            contextSource);
    userSearch.setReturningAttributes(roleAttributesGlob.split(","));
    this.delegate = new LdapUserDetailsService(userSearch);

    if (StringUtils.isNotBlank(roleAttributesGlob)) {
        LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
        mapper.setRoleAttributes(roleAttributesGlob.split(","));
        this.delegate.setUserDetailsMapper(mapper);
    }

    // Setup the caches
    cache = new MapMaker().maximumSize(cacheSize).expireAfterWrite(cacheExpiration, TimeUnit.MINUTES)
            .makeComputingMap(new Function<String, Object>() {
                public Object apply(String id) {
                    User user = loadUserFromLdap(id);
                    return user == null ? nullToken : user;
                }
            });

    registerMBean(pid);
}