Search in sources :

Example 1 with BindAuthenticator

use of org.springframework.security.ldap.authentication.BindAuthenticator in project nifi-registry by apache.

the class LdapIdentityProvider method onConfigured.

@Override
public final void onConfigured(final IdentityProviderConfigurationContext configurationContext) throws SecurityProviderCreationException {
    final String rawExpiration = configurationContext.getProperty("Authentication Expiration");
    if (StringUtils.isBlank(rawExpiration)) {
        throw new SecurityProviderCreationException("The Authentication Expiration must be specified.");
    }
    try {
        expiration = FormatUtils.getTimeDuration(rawExpiration, TimeUnit.MILLISECONDS);
    } catch (final IllegalArgumentException iae) {
        throw new SecurityProviderCreationException(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 SecurityProviderCreationException(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 SecurityProviderCreationException(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 SecurityProviderCreationException("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 SecurityProviderCreationException("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 SecurityProviderCreationException(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 SecurityProviderCreationException(e.getMessage(), e);
    }
    // create the underlying provider
    ldapAuthenticationProvider = new LdapAuthenticationProvider(authenticator);
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) HashMap(java.util.HashMap) SimpleDirContextAuthenticationStrategy(org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy) AbstractTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.AbstractTlsDirContextAuthenticationStrategy) SSLContext(javax.net.ssl.SSLContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.ldap.AuthenticationException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) KeyStoreException(java.security.KeyStoreException) IdentityAccessException(org.apache.nifi.registry.security.authentication.exception.IdentityAccessException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SecurityProviderDestructionException(org.apache.nifi.registry.security.exception.SecurityProviderDestructionException) InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapUserSearch(org.springframework.security.ldap.search.LdapUserSearch) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) DefaultTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy) AbstractLdapAuthenticationProvider(org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Example 2 with BindAuthenticator

use of org.springframework.security.ldap.authentication.BindAuthenticator in project atlas by apache.

the class AtlasLdapAuthenticationProvider method getLdapBindAuthentication.

private Authentication getLdapBindAuthentication(Authentication authentication) {
    try {
        if (isDebugEnabled) {
            LOG.debug("==> AtlasLdapAuthenticationProvider getLdapBindAuthentication");
        }
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }
        LdapContextSource ldapContextSource = getLdapContextSource();
        DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = getDefaultLdapAuthoritiesPopulator(ldapContextSource);
        if (ldapUserSearchFilter == null || ldapUserSearchFilter.trim().isEmpty()) {
            ldapUserSearchFilter = "(uid={0})";
        }
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(ldapBase, ldapUserSearchFilter, ldapContextSource);
        userSearch.setSearchSubtree(true);
        BindAuthenticator bindAuthenticator = getBindAuthenticator(userSearch, ldapContextSource);
        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator);
        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("LDAP Authentication::userName or userPassword is null or empty for userName " + userName);
        }
    } catch (Exception e) {
        LOG.error(" getLdapBindAuthentication LDAP Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasLdapAuthenticationProvider getLdapBindAuthentication");
    }
    return authentication;
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) User(org.apache.atlas.web.model.User) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) DefaultLdapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) AuthenticationException(org.springframework.security.core.AuthenticationException) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Example 3 with BindAuthenticator

use of org.springframework.security.ldap.authentication.BindAuthenticator in project atlas by apache.

the class AtlasADAuthenticationProvider method getADBindAuthentication.

private Authentication getADBindAuthentication(Authentication authentication) {
    try {
        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();
        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;
    }
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) User(org.apache.atlas.web.model.User) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider) ActiveDirectoryLdapAuthenticationProvider(org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider)

Example 4 with BindAuthenticator

use of org.springframework.security.ldap.authentication.BindAuthenticator in project midpoint by Evolveum.

the class LdapModuleFactory method getProvider.

private AuthenticationProvider getProvider(LdapAuthenticationModuleType moduleType) {
    DefaultSpringSecurityContextSource ctx = new DefaultSpringSecurityContextSource(moduleType.getHost());
    ctx.setUserDn(moduleType.getUserDn());
    try {
        ctx.setPassword(protector.decryptString(moduleType.getUserPassword()));
    } catch (EncryptionException e) {
        LOGGER.error("Couldn't obtain clear string for configuration of LDAP user password from " + moduleType.getUserPassword());
    }
    getObjectObjectPostProcessor().postProcess(ctx);
    BindAuthenticator auth = new BindAuthenticator(ctx);
    if (StringUtils.isNotEmpty(moduleType.getDnPattern())) {
        auth.setUserDnPatterns(new String[] { moduleType.getDnPattern() });
    }
    if (moduleType.getSearch() != null) {
        FilterBasedLdapUserSearch search = new FilterBasedLdapUserSearch("", moduleType.getSearch().getPattern(), ctx);
        if (moduleType.getSearch().isSubtree() != null) {
            search.setSearchSubtree(moduleType.getSearch().isSubtree());
        }
        getObjectObjectPostProcessor().postProcess(search);
        auth.setUserSearch(search);
    }
    getObjectObjectPostProcessor().postProcess(auth);
    MidPointLdapAuthenticationProvider provider = new MidPointLdapAuthenticationProvider(auth);
    provider.setUserDetailsContextMapper(new MidpointPrincipalContextMapper(principalManager));
    getObjectObjectPostProcessor().postProcess(provider.getAuthenticatorProvider());
    getObjectObjectPostProcessor().postProcess(provider);
    return provider;
}
Also used : MidpointPrincipalContextMapper(com.evolveum.midpoint.authentication.impl.ldap.MidpointPrincipalContextMapper) BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) MidPointLdapAuthenticationProvider(com.evolveum.midpoint.authentication.impl.provider.MidPointLdapAuthenticationProvider) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch)

Example 5 with BindAuthenticator

use of org.springframework.security.ldap.authentication.BindAuthenticator in project ontrack by nemerosa.

the class LDAPProviderFactoryImpl method loadProvider.

private LdapAuthenticationProvider loadProvider() {
    LDAPSettings settings = cachedSettingsService.getCachedSettings(LDAPSettings.class);
    if (settings.isEnabled()) {
        // LDAP context
        DefaultSpringSecurityContextSource ldapContextSource = new DefaultSpringSecurityContextSource(settings.getUrl());
        ldapContextSource.setUserDn(settings.getUser());
        ldapContextSource.setPassword(settings.getPassword());
        try {
            ldapContextSource.afterPropertiesSet();
        } catch (Exception e) {
            throw new CannotInitializeLDAPException(e);
        }
        // User search
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(settings.getSearchBase(), settings.getSearchFilter(), ldapContextSource);
        userSearch.setSearchSubtree(true);
        // Bind authenticator
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        // Provider
        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, authoritiesPopulator);
        ldapAuthenticationProvider.setUserDetailsContextMapper(new ConfigurableUserDetailsContextMapper(settings));
        // OK
        return ldapAuthenticationProvider;
    } else // LDAP not enabled
    {
        return null;
    }
}
Also used : BindAuthenticator(org.springframework.security.ldap.authentication.BindAuthenticator) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) FilterBasedLdapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Aggregations

BindAuthenticator (org.springframework.security.ldap.authentication.BindAuthenticator)19 LdapAuthenticationProvider (org.springframework.security.ldap.authentication.LdapAuthenticationProvider)14 LdapContextSource (org.springframework.ldap.core.support.LdapContextSource)13 FilterBasedLdapUserSearch (org.springframework.security.ldap.search.FilterBasedLdapUserSearch)12 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)11 Authentication (org.springframework.security.core.Authentication)11 GrantedAuthority (org.springframework.security.core.GrantedAuthority)11 UserDetails (org.springframework.security.core.userdetails.UserDetails)11 DefaultSpringSecurityContextSource (org.springframework.security.ldap.DefaultSpringSecurityContextSource)11 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)7 AuthenticationException (org.springframework.security.core.AuthenticationException)7 DefaultLdapAuthoritiesPopulator (org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator)7 User (org.apache.atlas.web.model.User)6 ArrayList (java.util.ArrayList)5 DefaultTlsDirContextAuthenticationStrategy (org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy)5 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)5 User (org.springframework.security.core.userdetails.User)5 ActiveDirectoryLdapAuthenticationProvider (org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider)5 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)3 IOException (java.io.IOException)2