Java Code Examples for org.springframework.ldap.core.support.LdapContextSource

The following examples show how to use org.springframework.ldap.core.support.LdapContextSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: blackduck-alert   Source File: LdapManager.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<LdapAuthenticationProvider> createAuthProvider(FieldAccessor configuration) throws AlertConfigurationException {
    try {
        boolean enabled = configuration.getBooleanOrFalse(AuthenticationDescriptor.KEY_LDAP_ENABLED);
        if (!enabled) {
            return Optional.empty();
        }
        LdapContextSource ldapContextSource = new LdapContextSource();

        String ldapServer = configuration.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_SERVER);
        String managerDN = configuration.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_MANAGER_DN);
        String managerPassword = configuration.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_MANAGER_PWD);
        String ldapReferral = configuration.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_REFERRAL);
        if (StringUtils.isNotBlank(ldapServer)) {
            ldapContextSource.setUrl(ldapServer);
            ldapContextSource.setUserDn(managerDN);
            ldapContextSource.setPassword(managerPassword);
            ldapContextSource.setReferral(ldapReferral);
            ldapContextSource.setAuthenticationStrategy(createAuthenticationStrategy(configuration));
        }
        ldapContextSource.afterPropertiesSet();
        return Optional.of(updateAuthenticationProvider(configuration, ldapContextSource));
    } catch (IllegalArgumentException ex) {
        throw new AlertConfigurationException("Error creating LDAP Context Source", ex);
    }
}
 
Example 2
Source Project: cuba   Source File: LdapLoginProvider.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void init() {
    if (webLdapConfig.getLdapEnabled()) {
        ldapContextSource = new LdapContextSource();

        checkRequiredConfigProperties(webLdapConfig);

        ldapContextSource.setBase(webLdapConfig.getLdapBase());
        List<String> ldapUrls = webLdapConfig.getLdapUrls();
        ldapContextSource.setUrls(ldapUrls.toArray(new String[ldapUrls.size()]));
        ldapContextSource.setUserDn(webLdapConfig.getLdapUser());
        ldapContextSource.setPassword(webLdapConfig.getLdapPassword());

        ldapContextSource.afterPropertiesSet();

        ldapTemplate = new LdapTemplate(ldapContextSource);
        ldapTemplate.setIgnorePartialResultException(true);
    }
}
 
Example 3
@Override
protected LdapContextSource createInstance() throws Exception {
    ContextSourceBuilder contextSourceBuilder = new ContextSourceBuilder();

    contextSourceBuilder
            .root(environment.getProperty("context.base"));

    // set up embedded mode
    if (environment.getProperty("embedded", boolean.class, false)) {
        contextSourceBuilder.ldif("classpath:/ldap/gravitee-io-management-rest-api-ldap-test.ldif");
    } else {
        contextSourceBuilder
                .managerDn(environment.getProperty("context.username"))
                .managerPassword(environment.getProperty("context.password"))
                .url(environment.getProperty("context.url"));
    }

    ldapContextSource = contextSourceBuilder.build();
    return ldapContextSource;
}
 
Example 4
Source Project: geofence   Source File: BaseDAOTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static void loadData() throws Exception
{
    // Bind to the directory
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:10389");
    contextSource.setUserDn("uid=admin,ou=system");
    contextSource.setPassword("secret");
    contextSource.setPooled(false);
    //contextSource.setDirObjectFactory(null);
    contextSource.afterPropertiesSet();

    // Create the Sprint LDAP template
    LdapTemplate template = new LdapTemplate(contextSource);

    // Clear out any old data - and load the test data
    LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName("dc=example,dc=com"));
    LdapTestUtils.loadLdif(contextSource, new ClassPathResource("data.ldif"));
}
 
Example 5
Source Project: ob1k   Source File: LdapCredentialsAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This constructor creates a LdapCredentialsAuthenticator that authenticates against an LDAP server
 * that supports anonymous requests
 *
 * @param ldapHost    the LDAP server host
 * @param ldapPort    the LDAP server port
 * @param usersOuPath the path for the organizational unit under which users are found
 */
public LdapCredentialsAuthenticator(final String ldapHost,
                                    final int ldapPort,
                                    final String usersOuPath) {
  Assert.hasText(ldapHost, "Invalid ldapHost");
  Assert.isTrue(ldapPort > 0);
  Assert.hasText(usersOuPath, "Invalid usersOuPath");

  final LdapContextSource contextSource = new LdapContextSource();
  contextSource.setAnonymousReadOnly(true);
  contextSource.setUrl("ldap://" + ldapHost + ":" + ldapPort);
  contextSource.setBase(usersOuPath);
  contextSource.afterPropertiesSet();

  ldapTemplate = new LdapTemplate(contextSource);
  this.id = calculateId(ldapHost, ldapPort, usersOuPath);
}
 
Example 6
Source Project: ob1k   Source File: LdapCredentialsAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This constructor creates a LdapCredentialsAuthenticator that authenticates against an LDAP server
 * that does not support anonymous requests
 *
 * @param ldapHost    the LDAP server host
 * @param ldapPort    the LDAP server port
 * @param usersOuPath the path for the organizational unit under which users are found
 * @param userDn      the distinguished name for the connection
 * @param password    the password for the connection
 */
public LdapCredentialsAuthenticator(final String ldapHost,
                                    final int ldapPort,
                                    final String usersOuPath,
                                    final String userDn,
                                    final String password) {
  Assert.hasText(ldapHost, "Invalid ldapHost");
  Assert.isTrue(ldapPort > 0);
  Assert.hasText(usersOuPath, "Invalid usersOuPath");
  Assert.hasText(userDn, "Invalid userDn");
  Assert.hasText(password, "Invalid password");

  final LdapContextSource contextSource = new LdapContextSource();
  contextSource.setUrl("ldap://" + ldapHost + ":" + ldapPort);
  contextSource.setBase(usersOuPath);
  contextSource.setUserDn(userDn);
  contextSource.setPassword(password);
  contextSource.afterPropertiesSet();

  ldapTemplate = new LdapTemplate(contextSource);
  this.id = calculateId(ldapHost, ldapPort, usersOuPath);
}
 
Example 7
@BeforeClass
public static void startLDAPServer() throws Exception {
    LdapTestUtils.startApacheDirectoryServer(PORT, baseName.toString(), "test", PRINCIPAL, CREDENTIALS, null);
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:" + PORT);
    contextSource.setUserDn("");
    contextSource.setPassword("");
    contextSource.setPooled(false);
    contextSource.afterPropertiesSet();

    // Create the Sprint LDAP template
    LdapTemplate template = new LdapTemplate(contextSource);

    // Clear out any old data - and load the test data
    LdapTestUtils.cleanAndSetup(template.getContextSource(), baseName, new ClassPathResource("ldap/testdata.ldif"));
    System.out.println("____________Started LDAP_________");
}
 
Example 8
@Test
public void testGetReadOnlyContext() throws NamingException {
	DirContext ctx = null;

	try {
		ctx = tested.getReadOnlyContext();
		assertThat(ctx).isNotNull();
		Hashtable environment = ctx.getEnvironment();
		assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse();
		assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue();
		assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue();
	}
	finally {
		// Always clean up.
		if (ctx != null) {
			try {
				ctx.close();
			}
			catch (Exception e) {
				// Never mind this
			}
		}
	}
}
 
Example 9
@Test
public void testGetReadWriteContext() throws NamingException {
	DirContext ctx = null;

	try {
		ctx = tested.getReadWriteContext();
		assertThat(ctx).isNotNull();
		// Double check to see that we are authenticated.
		Hashtable environment = ctx.getEnvironment();
           assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse();
		assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue();
		assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue();
	}
	finally {
		// Always clean up.
		if (ctx != null) {
			try {
				ctx.close();
			}
			catch (Exception e) {
				// Never mind this
			}
		}
	}
}
 
Example 10
private String accountAsUserDn2Authentication(String loginName, LdapE ldap, LdapContextSource contextSource, AndFilter filter) {
    contextSource.setUserDn(ldap.getAccount());
    contextSource.setPassword(ldap.getPassword());
    contextSource.afterPropertiesSet();
    LdapTemplate template = new LdapTemplate(contextSource);
    if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
        template.setIgnorePartialResultException(true);
    }
    String userDn = null;
    try {
        List<String> names =
                template.search(
                        query()
                                .searchScope(SearchScope.SUBTREE)
                                .filter(filter),
                        new AbstractContextMapper() {
                            @Override
                            protected Object doMapFromContext(DirContextOperations ctx) {
                                return ctx.getNameInNamespace();
                            }
                        });
        userDn = getUserDn(names, ldap.getLoginNameField(), loginName);
    } catch (Exception e) {
        LOG.error("use ldap account as userDn and password to authentication but search failed, filter {}," +
                " maybe the account or password is illegal, and check for the ldap config, exception {}", filter, e);
    }
    return userDn;
}
 
Example 11
private boolean authentication(String credentials, LdapContextSource contextSource, String userDn) {
    DirContext ctx = null;
    try {
        ctx = contextSource.getContext(userDn, credentials);
        return true;
    } catch (Exception e) {
        LOG.error("Login failed, userDn or credentials may be wrong, exception {}", e);
        return false;
    } finally {
        // It is imperative that the created DirContext instance is always closed
        LdapUtils.closeContext(ctx);
    }
}
 
Example 12
Source Project: Spring-5.0-Projects   Source File: LdapDataConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public ContextSource getLdapContextSrc() {
	LdapContextSource ldapContextSrc = new LdapContextSource();
	ldapContextSrc.setUrl(ldapUrls);
	ldapContextSrc.setUserDn(ldapManagerUserName);
	ldapContextSrc.setPassword(ldapManagerPwd);
	ldapContextSrc.setBase(ldapBase);
	ldapContextSrc.afterPropertiesSet();
	return ldapContextSrc;
}
 
Example 13
Source Project: Gatekeeper   Source File: GatekeeperCommonConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.ldap.context-source")
public LdapContextSource authContextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setBase(userBase);
    return contextSource;
}
 
Example 14
Source Project: heimdall   Source File: TokenAuthenticationService.java    License: Apache License 2.0 5 votes vote down vote up
private LdapAuthenticationProvider ldapProvider(Ldap ldap) {

        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldap.getUrl());
        contextSource.setUserDn(ldap.getUserDn());
        contextSource.setPassword(ldap.getPassword());
        contextSource.setReferral("follow");
        contextSource.afterPropertiesSet();

        LdapUserSearch ldapUserSearch = new FilterBasedLdapUserSearch(ldap.getSearchBase(), ldap.getUserSearchFilter(), contextSource);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource);
        bindAuthenticator.setUserSearch(ldapUserSearch);
        return new LdapAuthenticationProvider(bindAuthenticator, populator);
    }
 
Example 15
Source Project: atlas   Source File: AtlasLdapAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
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);
    ldapContextSource.afterPropertiesSet();
    return ldapContextSource;
}
 
Example 16
Source Project: atlas   Source File: AtlasLdapAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
private DefaultLdapAuthoritiesPopulator getDefaultLdapAuthoritiesPopulator(
        LdapContextSource ldapContextSource) {
    DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
            ldapContextSource, ldapGroupSearchBase);
    defaultLdapAuthoritiesPopulator
            .setGroupRoleAttribute(ldapGroupRoleAttribute);
    defaultLdapAuthoritiesPopulator
            .setGroupSearchFilter(ldapGroupSearchFilter);
    defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);
    return defaultLdapAuthoritiesPopulator;
}
 
Example 17
Source Project: atlas   Source File: AtlasLdapAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 18
Source Project: taskana   Source File: LdapConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(LdapContextSource.class)
public LdapContextSource ldapContextSource() {
  LdapContextSource contextSource = new LdapContextSource();
  contextSource.setUrl(ldapServerUrl);
  contextSource.setBase(ldapBaseDn);
  contextSource.setUserDn(ldapBindDn);
  contextSource.setPassword(ldapBindPassword);
  return contextSource;
}
 
Example 19
Source Project: blackduck-alert   Source File: LdapManager.java    License: Apache License 2.0 5 votes vote down vote up
private LdapAuthenticator createAuthenticator(FieldAccessor configurationModel, LdapContextSource contextSource) throws AlertConfigurationException {
    BindAuthenticator authenticator = new BindAuthenticator(contextSource);
    try {
        String[] userDnArray = createArrayFromCSV(configurationModel.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_USER_DN_PATTERNS));
        String[] userAttributeArray = createArrayFromCSV(configurationModel.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_USER_ATTRIBUTES));
        authenticator.setUserSearch(createLdapUserSearch(configurationModel, contextSource));
        authenticator.setUserDnPatterns(userDnArray);
        authenticator.setUserAttributes(userAttributeArray);
        authenticator.afterPropertiesSet();
    } catch (Exception ex) {
        throw new AlertConfigurationException("Error creating LDAP authenticator", ex);
    }
    return authenticator;
}
 
Example 20
Source Project: blackduck-alert   Source File: LdapManager.java    License: Apache License 2.0 5 votes vote down vote up
private LdapAuthoritiesPopulator createAuthoritiesPopulator(FieldAccessor configurationModel, LdapContextSource contextSource) {
    String groupSearchBase = configurationModel.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_GROUP_SEARCH_BASE);
    String groupSearchFilter = configurationModel.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_GROUP_SEARCH_FILTER);
    String groupRoleAttribute = configurationModel.getStringOrEmpty(AuthenticationDescriptor.KEY_LDAP_GROUP_ROLE_ATTRIBUTE);
    MappingLdapAuthoritiesPopulator mappingLdapAuthoritiesPopulator = new MappingLdapAuthoritiesPopulator(contextSource, groupSearchBase, this.authoritiesPopulator);
    mappingLdapAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
    mappingLdapAuthoritiesPopulator.setGroupRoleAttribute(groupRoleAttribute);
    // expect the LDAP group name for the role to be ROLE_<ROLE_NAME> where ROLE_NAME defined in UserRoles
    // Set the prefix to the empty string because the prefix is by default set to ROLE_ we don't want the populator to create ROLE_ROLE_<ROLE_NAME> due to the default prefix
    mappingLdapAuthoritiesPopulator.setRolePrefix("");
    return mappingLdapAuthoritiesPopulator;
}
 
Example 21
Source Project: incubator-wikift   Source File: LdapConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public LdapTemplate ldapTemplate() {
    if (!ObjectUtils.isEmpty(contextSource())) {
        return new LdapTemplate(contextSource());
    }
    return new LdapTemplate(new LdapContextSource());
}
 
Example 22
Source Project: apollo   Source File: AuthConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
  LdapContextSource source = new LdapContextSource();
  source.setUserDn(this.properties.getUsername());
  source.setPassword(this.properties.getPassword());
  source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
  source.setBase(this.properties.getBase());
  source.setUrls(this.properties.determineUrls(this.environment));
  source.setBaseEnvironmentProperties(
      Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
  return source;
}
 
Example 23
Source Project: apollo   Source File: AuthConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties,
    final LdapContextSource ldapContextSource,
   final LdapExtendProperties ldapExtendProperties) {
  this.ldapProperties = ldapProperties;
  this.ldapContextSource = ldapContextSource;
  this.ldapExtendProperties = ldapExtendProperties;
}
 
Example 24
Source Project: herd   Source File: LdapOperationsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch()
{
    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(LDAP_URL);
    contextSource.setBase(LDAP_BASE);
    contextSource.setUserDn(LDAP_USER_DN);
    contextSource.setPassword(PASSWORD);
    contextSource.afterPropertiesSet();

    // Create an LDAP template.
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_ID.getDefaultValue()).is(USER_ID);

    // Create a subject matter expert contact details mapper.
    SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
        new SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER.getDefaultValue());

    // Gets information for the specified subject matter expert.
    List<SubjectMatterExpertContactDetails> result = ldapOperations.search(ldapTemplate, ldapQuery, subjectMatterExpertContactDetailsMapper);

    // Validate the results.
    assertEquals(
        Collections.singletonList(new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER)),
        result);
}
 
Example 25
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);
    ldapContextSource.afterPropertiesSet();
    return ldapContextSource;
}
 
Example 26
private DefaultLdapAuthoritiesPopulator getDefaultLdapAuthoritiesPopulator(
        LdapContextSource ldapContextSource) {
    DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
            ldapContextSource, ldapGroupSearchBase);
    defaultLdapAuthoritiesPopulator
            .setGroupRoleAttribute(ldapGroupRoleAttribute);
    defaultLdapAuthoritiesPopulator
            .setGroupSearchFilter(ldapGroupSearchFilter);
    defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);
    return defaultLdapAuthoritiesPopulator;
}
 
Example 27
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;
}
 
Example 28
Source Project: metron   Source File: LdapConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public LdapTemplate ldapTemplate() {
  LdapContextSource contextSource = new LdapContextSource();

  contextSource.setUrl(environment.getProperty(LDAP_PROVIDER_URL_SPRING_PROPERTY));
  contextSource.setUserDn(environment.getProperty(LDAP_PROVIDER_USERDN_SPRING_PROPERTY));
  contextSource.setPassword(environment.getProperty(LDAP_PROVIDER_PASSWORD_SPRING_PROPERTY));
  contextSource.afterPropertiesSet();

  return new LdapTemplate(contextSource);
}
 
Example 29
Source Project: ranger   Source File: AuthenticationCheck.java    License: Apache License 2.0 5 votes vote down vote up
private Authentication getADBindAuthentication(String ldapUrl, String bindDn, String bindPassword,
                                               String userName, String userPassword) {
    Authentication result = null;
    try {
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
        ldapContextSource.setUserDn(bindDn);
        ldapContextSource.setPassword(bindPassword);
        ldapContextSource.setReferral("follow");
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        String searchFilter="(sAMAccountName={0})";
        FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adDomain, searchFilter,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 = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);

            result = ldapAuthenticationProvider.authenticate(finalAuthentication);
        }

    } catch (BadCredentialsException bce) {
        logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " +
                "ranger.admin.auth.samplepassword\n");
    } catch (Exception e) {
        logFile.println("ERROR: LDAP Authentication Failed: " + e);
    }
    return result;
}
 
Example 30
Source Project: spring-ldap   Source File: TestSchemaToJava.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // Create some basic converters and a converter manager
    converterManager = new ConverterManagerImpl();

    Converter ptc = new FromStringConverter();
    converterManager.addConverter(String.class, "", Byte.class, ptc);
    converterManager.addConverter(String.class, "", Short.class, ptc);
    converterManager.addConverter(String.class, "", Integer.class, ptc);
    converterManager.addConverter(String.class, "", Long.class, ptc);
    converterManager.addConverter(String.class, "", Double.class, ptc);
    converterManager.addConverter(String.class, "", Float.class, ptc);
    converterManager.addConverter(String.class, "", Boolean.class, ptc);

    Converter tsc = new ToStringConverter();
    converterManager.addConverter(Byte.class, "", String.class, tsc);
    converterManager.addConverter(Short.class, "", String.class, tsc);
    converterManager.addConverter(Integer.class, "", String.class, tsc);
    converterManager.addConverter(Long.class, "", String.class, tsc);
    converterManager.addConverter(Double.class, "", String.class, tsc);
    converterManager.addConverter(Float.class, "", String.class, tsc);
    converterManager.addConverter(Boolean.class, "", String.class, tsc);

    // Bind to the directory
    contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:" + port);
    contextSource.setUserDn("");
    contextSource.setPassword("");
    contextSource.setPooled(false);
    contextSource.afterPropertiesSet();

    // Clear out any old data - and load the test data
    LdapTestUtils.cleanAndSetup(contextSource, baseName, new ClassPathResource("testdata.ldif"));
}