Search in sources :

Example 16 with DefaultSpringSecurityContextSource

use of org.springframework.security.ldap.DefaultSpringSecurityContextSource in project service-authorization by reportportal.

the class LdapAuthProvider method getDelegate.

@Override
protected AuthenticationProvider getDelegate() {
    Integration integration = integrationRepository.findAllByTypeIn(AuthIntegrationType.LDAP.getName()).stream().findFirst().orElseThrow(() -> new BadCredentialsException("LDAP is not configured"));
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(singletonList(LdapParameter.URL.getRequiredParameter(integration)), LdapParameter.BASE_DN.getRequiredParameter(integration));
    LdapParameter.MANAGER_PASSWORD.getParameter(integration).ifPresent(it -> contextSource.setPassword(encryptor.decrypt(it)));
    LdapParameter.MANAGER_DN.getParameter(integration).ifPresent(contextSource::setUserDn);
    contextSource.afterPropertiesSet();
    LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> builder = new LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>().contextSource(contextSource).ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator()).userDetailsContextMapper(detailsContextMapper);
    /*
		 * Basically, groups are not used
		 */
    LdapParameter.GROUP_SEARCH_FILTER.getParameter(integration).ifPresent(builder::groupSearchFilter);
    LdapParameter.GROUP_SEARCH_BASE.getParameter(integration).ifPresent(builder::groupSearchBase);
    LdapParameter.USER_SEARCH_FILTER.getParameter(integration).ifPresent(builder::userSearchFilter);
    LdapParameter.PASSWORD_ENCODER_TYPE.getParameter(integration).ifPresent(it -> {
        LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>.PasswordCompareConfigurer passwordCompareConfigurer = builder.passwordCompare();
        LdapParameter.PASSWORD_ATTRIBUTE.getParameter(integration).ifPresent(passwordCompareConfigurer::passwordAttribute);
        /*
			 * DIRTY HACK. If LDAP's password has solt, ldaptemplate.compare operation does not work
			 * since we don't know server's salt.
			 * To enable local password comparison, we need to provide password encoder from crypto's package
			 * This is why we just wrap old encoder with new one interface
			 * New encoder cannot be used everywhere since it does not have implementation for LDAP
			 */
        final PasswordEncoder delegate = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        builder.passwordEncoder(new org.springframework.security.crypto.password.PasswordEncoder() {

            @Override
            public String encode(CharSequence rawPassword) {
                return delegate.encode(rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return delegate.matches(rawPassword, encodedPassword);
            }
        });
    });
    LdapParameter.USER_DN_PATTERN.getParameter(integration).ifPresent(builder::userDnPatterns);
    try {
        return (AuthenticationProvider) Accessible.on(builder).method(LdapAuthenticationProviderConfigurer.class.getDeclaredMethod("build")).invoke();
    } catch (Throwable e) {
        throw new ReportPortalException("Cannot build LDAP auth provider", e);
    }
}
Also used : Integration(com.epam.ta.reportportal.entity.integration.Integration) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ReportPortalException(com.epam.ta.reportportal.exception.ReportPortalException) NullLdapAuthoritiesPopulator(org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator) LdapAuthenticationProviderConfigurer(org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer)

Example 17 with DefaultSpringSecurityContextSource

use of org.springframework.security.ldap.DefaultSpringSecurityContextSource in project gocd by gocd.

the class ServerConfigService method ldapContextSource.

DefaultSpringSecurityContextSource ldapContextSource(LdapConfig ldapConfig) {
    DefaultSpringSecurityContextSource source = new DefaultSpringSecurityContextSource(ldapConfig.uri());
    //so user can define the variable java.naming.referral=follow in the server.sh
    source.setBaseEnvironmentProperties(System.getProperties());
    new LdapContextSourceConfigurator(ldapConfig).configure(source);
    try {
        source.afterPropertiesSet();
    } catch (Exception e) {
        bomb("Cannot create ldap context", e);
    }
    return source;
}
Also used : DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) LdapContextSourceConfigurator(com.thoughtworks.go.server.security.LdapContextSourceConfigurator) URISyntaxException(java.net.URISyntaxException) AddressException(javax.mail.internet.AddressException)

Example 18 with DefaultSpringSecurityContextSource

use of org.springframework.security.ldap.DefaultSpringSecurityContextSource in project gocd by gocd.

the class ServerConfigServiceIntegrationTest method shouldUseTheEncryptedPasswordWhenPasswordIsNotChanged.

@Test
public void shouldUseTheEncryptedPasswordWhenPasswordIsNotChanged() throws InvalidCipherTextException {
    String encryptedPassword = new GoCipher().encrypt("encrypted_password");
    LdapConfig ldapConfig = new LdapConfig(LDAP_URL, MANAGER_DN, MANAGER_PASSWORD, encryptedPassword, false, new BasesConfig(new BaseConfig(SEARCH_BASE)), SEARCH_FILTER);
    DefaultSpringSecurityContextSource source = serverConfigService.ldapContextSource(ldapConfig);
    assertThat(source.getAuthenticationSource().getCredentials(), is("encrypted_password"));
}
Also used : DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) GoCipher(com.thoughtworks.go.security.GoCipher) StringContains.containsString(org.hamcrest.core.StringContains.containsString) BasesConfig(com.thoughtworks.go.config.server.security.ldap.BasesConfig) BaseConfig(com.thoughtworks.go.config.server.security.ldap.BaseConfig) Test(org.junit.Test)

Example 19 with DefaultSpringSecurityContextSource

use of org.springframework.security.ldap.DefaultSpringSecurityContextSource in project gravitee-management-rest-api by gravitee-io.

the class LdapAuthenticationProvider method configure.

@Override
public SecurityConfigurer configure() throws Exception {
    LOGGER.info("Configuring an LDAP Identity Provider");
    LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = new LdapAuthenticationProviderConfigurer<>();
    // Create LDAP context
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(environment.getProperty("context-source-url"));
    contextSource.setBase(environment.getProperty("context-source-base"));
    contextSource.setUserDn(environment.getProperty("context-source-username"));
    contextSource.setPassword(environment.getProperty("context-source-password"));
    contextSource.afterPropertiesSet();
    String userDNPattern = environment.getProperty("user-dn-pattern");
    if (userDNPattern == null || userDNPattern.isEmpty()) {
        ldapAuthenticationProviderConfigurer.userSearchBase(environment.getProperty("user-search-base")).userSearchFilter(environment.getProperty("user-search-filter"));
    } else {
        ldapAuthenticationProviderConfigurer.userDnPatterns(userDNPattern);
    }
    ldapAuthenticationProviderConfigurer.groupSearchBase(environment.getProperty("group-search-base", "")).groupSearchFilter(environment.getProperty("group-search-filter", "(uniqueMember={0})")).groupRoleAttribute(environment.getProperty("group-role-attribute", "cn")).rolePrefix("");
    DefaultLdapAuthoritiesPopulator populator = new DefaultLdapAuthoritiesPopulator(contextSource, environment.getProperty("group-search-base", ""));
    populator.setRolePrefix("");
    ldapAuthenticationProviderConfigurer.ldapAuthoritiesPopulator(populator).contextSource(contextSource);
    // set up LDAP mapper
    UserDetailsContextPropertiesMapper userDetailsContextPropertiesMapper = new UserDetailsContextPropertiesMapper();
    userDetailsContextPropertiesMapper.setEnvironment(environment);
    userDetailsContextPropertiesMapper.afterPropertiesSet();
    ldapAuthenticationProviderConfigurer.userDetailsContextMapper(userDetailsContextPropertiesMapper);
    return ldapAuthenticationProviderConfigurer;
}
Also used : DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) DefaultLdapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator)

Example 20 with DefaultSpringSecurityContextSource

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

the class AtlasLdapAuthenticationProvider method getLdapAuthentication.

private Authentication getLdapAuthentication(Authentication authentication) {
    if (isDebugEnabled) {
        LOG.debug("==> AtlasLdapAuthenticationProvider getLdapAuthentication");
    }
    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;
}
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) 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) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Aggregations

DefaultSpringSecurityContextSource (org.springframework.security.ldap.DefaultSpringSecurityContextSource)31 LdapContextSource (org.springframework.ldap.core.support.LdapContextSource)12 BindAuthenticator (org.springframework.security.ldap.authentication.BindAuthenticator)11 LdapAuthenticationProvider (org.springframework.security.ldap.authentication.LdapAuthenticationProvider)10 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 Authentication (org.springframework.security.core.Authentication)9 GrantedAuthority (org.springframework.security.core.GrantedAuthority)9 UserDetails (org.springframework.security.core.userdetails.UserDetails)9 FilterBasedLdapUserSearch (org.springframework.security.ldap.search.FilterBasedLdapUserSearch)8 Test (org.junit.jupiter.api.Test)7 DefaultLdapAuthoritiesPopulator (org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator)7 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)6 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)6 ArrayList (java.util.ArrayList)5 AuthenticationException (org.springframework.security.core.AuthenticationException)5 User (org.springframework.security.core.userdetails.User)5 ActiveDirectoryLdapAuthenticationProvider (org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider)5 User (org.apache.atlas.web.model.User)4 DefaultTlsDirContextAuthenticationStrategy (org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy)4 Bean (org.springframework.context.annotation.Bean)3