Example usage for org.springframework.security.ldap.authentication BindAuthenticator BindAuthenticator

List of usage examples for org.springframework.security.ldap.authentication BindAuthenticator BindAuthenticator

Introduction

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

Prototype

public BindAuthenticator(BaseLdapPathContextSource contextSource) 

Source Link

Document

Create an initialized instance using the BaseLdapPathContextSource provided.

Usage

From source file:com.evolveum.midpoint.web.boot.LdapSecurityConfig.java

@Bean
public BindAuthenticator bindAuthenticator() {
    BindAuthenticator auth = new BindAuthenticator(contextSource());
    if (StringUtils.isNotEmpty(ldapDnPattern)) {
        auth.setUserDnPatterns(new String[] { ldapDnPattern });
    }//w w  w  . ja v  a2s  .c o m
    if (StringUtils.isNotEmpty(ldapSearchPattern)) {
        auth.setUserSearch(userSearch());
    }

    return auth;
}

From source file:de.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSpring() throws Exception {
    DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
            "ldap://ldap.xxx:389/OU=xxx");

    ctxSrc.setUserDn(USER_LDAP);// www. j  a v  a2s .com
    ctxSrc.setPassword(PASSWORD_LDAP);

    ctxSrc.afterPropertiesSet();

    logger.info("Base LDAP Path: " + ctxSrc.getBaseLdapPath());
    logger.info("Principal: " + ctxSrc.getAuthenticationSource().getPrincipal().toString());
    logger.info("Credentials: " + ctxSrc.getAuthenticationSource().getCredentials());

    Authentication bob = new UsernamePasswordAuthenticationToken("bob", "bob");

    BindAuthenticator authenticator = new BindAuthenticator(ctxSrc);
    authenticator.setUserSearch(
            new FilterBasedLdapUserSearch("", "(&(objectCategory=Person)(sAMAccountName={0}))", ctxSrc));
    authenticator.afterPropertiesSet();

    authenticator.authenticate(bob);

    DirContextOperations user = authenticator.authenticate(bob);

    logger.info("User: {}", user);
}

From source file:org.osiam.configuration.LdapAuthentication.java

@Bean
public LdapAuthenticator bindAuthenticator() {
    BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource());
    bindAuthenticator.setUserDnPatterns(dnPatterns);
    bindAuthenticator/*w w  w .  j  a v  a  2s . c  o m*/
            .setUserAttributes(Iterables.toArray(ldapToScimAttributeMapping().ldapAttributes(), String.class));
    return bindAuthenticator;
}

From source file:org.osiam.auth.configuration.LdapConfiguration.java

@Bean
public OsiamLdapAuthenticationProvider createLdapAuthProvider() {
    if (isLdapConfigured) {

        createLdapToScimAttributeMapping();

        DefaultSpringSecurityContextSource contextSource = createLdapContextSource();

        BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource);
        bindAuthenticator.setUserDnPatterns(dnPatterns);
        bindAuthenticator.setUserAttributes(attributes);

        OsiamLdapUserContextMapper mapper = new OsiamLdapUserContextMapper(scimLdapAttributes);
        DefaultLdapAuthoritiesPopulator authoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
                contextSource, groupSearchBase);

        OsiamLdapAuthenticationProvider provider = new OsiamLdapAuthenticationProvider(bindAuthenticator,
                authoritiesPopulator, mapper);

        authenticationManager.getProviders().add(provider);

        return provider;
    }/*w ww .  jav  a2s.  c  om*/
    return null;
}

From source file:io.gravitee.management.idp.ldap.authentication.LdapAuthenticationProviderConfigurer.java

/**
 * Creates a {@link BindAuthenticator}/*from  ww w  .ja  v a  2s.co m*/
 *
 * @param contextSource the {@link BaseLdapPathContextSource} to use
 * @return the {@link BindAuthenticator} to use
 */
private BindAuthenticator createBindAuthenticator(BaseLdapPathContextSource contextSource) {
    return new BindAuthenticator(contextSource);
}

From source file:de.thm.arsnova.config.SecurityConfig.java

@Bean
public LdapAuthenticator ldapAuthenticator() throws Exception {
    BindAuthenticator authenticator = new BindAuthenticator(ldapContextSource());
    authenticator.setUserDnPatterns(new String[] { ldapUserDn });

    return authenticator;
}

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

private Authentication getADBindAuthentication(Authentication authentication) {
    try {//from  w ww. ja  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");
    }/*  w  w  w. ja  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 BindAuthenticator getBindAuthenticator(FilterBasedLdapUserSearch userSearch,
        LdapContextSource ldapContextSource) throws Exception {
    BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
    bindAuthenticator.setUserSearch(userSearch);
    String[] userDnPatterns = new String[] { ldapUserDNPattern };
    bindAuthenticator.setUserDnPatterns(userDnPatterns);
    bindAuthenticator.afterPropertiesSet();
    return bindAuthenticator;
}

From source file:org.apache.nifi.ldap.LdapProvider.java

@Override
public final void onConfigured(final LoginIdentityProviderConfigurationContext configurationContext)
        throws ProviderCreationException {
    final String rawExpiration = configurationContext.getProperty("Authentication Expiration");
    if (StringUtils.isBlank(rawExpiration)) {
        throw new ProviderCreationException("The Authentication Expiration must be specified.");
    }//w  ww.java2 s. c  o m

    try {
        expiration = FormatUtils.getTimeDuration(rawExpiration, TimeUnit.MILLISECONDS);
    } catch (final IllegalArgumentException iae) {
        throw new ProviderCreationException(
                String.format("The Expiration Duration '%s' is not a valid time duration", rawExpiration));
    }

    final LdapContextSource context = new LdapContextSource();

    final Map<String, Object> baseEnvironment = new HashMap<>();

    // connect/read time out
    setTimeout(configurationContext, baseEnvironment, "Connect Timeout", "com.sun.jndi.ldap.connect.timeout");
    setTimeout(configurationContext, baseEnvironment, "Read Timeout", "com.sun.jndi.ldap.read.timeout");

    // authentication strategy
    final String rawAuthenticationStrategy = configurationContext.getProperty("Authentication Strategy");
    final LdapAuthenticationStrategy authenticationStrategy;
    try {
        authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy);
    } catch (final IllegalArgumentException iae) {
        throw new ProviderCreationException(String.format(
                "Unrecognized authentication strategy '%s'. Possible values are [%s]",
                rawAuthenticationStrategy, StringUtils.join(LdapAuthenticationStrategy.values(), ", ")));
    }

    switch (authenticationStrategy) {
    case ANONYMOUS:
        context.setAnonymousReadOnly(true);
        break;
    default:
        final String userDn = configurationContext.getProperty("Manager DN");
        final String password = configurationContext.getProperty("Manager Password");

        context.setUserDn(userDn);
        context.setPassword(password);

        switch (authenticationStrategy) {
        case SIMPLE:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());
            break;
        case LDAPS:
            context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());

            // indicate a secure connection
            baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");

            // get the configured ssl context
            final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext);
            if (ldapsSslContext != null) {
                // initialize the ldaps socket factory prior to use
                LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory());
                baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName());
            }
            break;
        case START_TLS:
            final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy();

            // shutdown gracefully
            final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully");
            if (StringUtils.isNotBlank(rawShutdownGracefully)) {
                final boolean shutdownGracefully = Boolean.TRUE.toString()
                        .equalsIgnoreCase(rawShutdownGracefully);
                tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully);
            }

            // get the configured ssl context
            final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext);
            if (startTlsSslContext != null) {
                tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory());
            }

            // set the authentication strategy
            context.setAuthenticationStrategy(tlsAuthenticationStrategy);
            break;
        }
        break;
    }

    // referrals
    final String rawReferralStrategy = configurationContext.getProperty("Referral Strategy");

    final ReferralStrategy referralStrategy;
    try {
        referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy);
    } catch (final IllegalArgumentException iae) {
        throw new ProviderCreationException(
                String.format("Unrecognized referral strategy '%s'. Possible values are [%s]",
                        rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", ")));
    }

    // using the value as this needs to be the lowercase version while the value is configured with the enum constant
    context.setReferral(referralStrategy.getValue());

    // url
    final String urls = configurationContext.getProperty("Url");

    if (StringUtils.isBlank(urls)) {
        throw new ProviderCreationException("LDAP identity provider 'Url' must be specified.");
    }

    // connection
    context.setUrls(StringUtils.split(urls));

    // search criteria
    final String userSearchBase = configurationContext.getProperty("User Search Base");
    final String userSearchFilter = configurationContext.getProperty("User Search Filter");

    if (StringUtils.isBlank(userSearchBase) || StringUtils.isBlank(userSearchFilter)) {
        throw new ProviderCreationException(
                "LDAP identity provider 'User Search Base' and 'User Search Filter' must be specified.");
    }

    final LdapUserSearch userSearch = new FilterBasedLdapUserSearch(userSearchBase, userSearchFilter, context);

    // bind
    final BindAuthenticator authenticator = new BindAuthenticator(context);
    authenticator.setUserSearch(userSearch);

    // identity strategy
    final String rawIdentityStrategy = configurationContext.getProperty("Identity Strategy");

    if (StringUtils.isBlank(rawIdentityStrategy)) {
        logger.info(String.format("Identity Strategy is not configured, defaulting strategy to %s.",
                IdentityStrategy.USE_DN));

        // if this value is not configured, default to use dn which was the previous implementation
        identityStrategy = IdentityStrategy.USE_DN;
    } else {
        try {
            // attempt to get the configured identity strategy
            identityStrategy = IdentityStrategy.valueOf(rawIdentityStrategy);
        } catch (final IllegalArgumentException iae) {
            throw new ProviderCreationException(
                    String.format("Unrecognized identity strategy '%s'. Possible values are [%s]",
                            rawIdentityStrategy, StringUtils.join(IdentityStrategy.values(), ", ")));
        }
    }

    // set the base environment is necessary
    if (!baseEnvironment.isEmpty()) {
        context.setBaseEnvironmentProperties(baseEnvironment);
    }

    try {
        // handling initializing beans
        context.afterPropertiesSet();
        authenticator.afterPropertiesSet();
    } catch (final Exception e) {
        throw new ProviderCreationException(e.getMessage(), e);
    }

    // create the underlying provider
    provider = new LdapAuthenticationProvider(authenticator);
}