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

The following java examples will help you to understand the usage of org.springframework.ldap.core.support.LdapContextSource. These source code samples are taken from different open source projects.

Example 1
Project: alien4cloud-master  File: LdapConfiguration.java View source code
@Bean
public LdapContextSource ldapContextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setAnonymousReadOnly(anonymousReadOnly);
    contextSource.setUrl(url);
    contextSource.setBase(base);
    contextSource.setUserDn(userDn);
    contextSource.setPassword(password);
    return contextSource;
}
Example 2
Project: cas-addons-master  File: CasNamespaceHandler.java View source code
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    //Configure LdapContextSource and main BindLdapAuthenticationHandler beans
    final BeanDefinitionBuilder contextSourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(LdapContextSource.class);
    parseBindLdapAuthenticationHandlerBeanDefinition(element, contextSourceBuilder, builder, parserContext.getRegistry());
}
Example 3
Project: ldap-test-utils-master  File: Utils.java View source code
public static LdapTemplate ldapTemplate(String bindDn, String password, int port) {
    LdapTemplate t = new LdapTemplate();
    LdapContextSource s = new LdapContextSource();
    s.setPassword(password);
    s.setUserDn(bindDn);
    s.setUrl(String.format("ldap://localhost:%d", port));
    t.setContextSource(s);
    try {
        t.afterPropertiesSet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    s.afterPropertiesSet();
    return t;
}
Example 4
Project: OpenConext-teams-master  File: Application.java View source code
@Bean
public UserDetailsManager userDetailsManager(@Value("${ldap.url}") String url, @Value("${ldap.base}") String base, @Value("${ldap.userDn}") String userDn, @Value("${ldap.password}") String password) {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(url);
    contextSource.setBase(base);
    contextSource.setUserDn(userDn);
    contextSource.setPassword(password);
    contextSource.afterPropertiesSet();
    return new LdapUserDetailsManager(new LdapTemplate(contextSource));
}
Example 5
Project: gluster-ovirt-poc-master  File: LdapTester.java View source code
public void internalTestGetUserByUserNameCommand(LdapContextSource ldapCtx) throws Exception {
    Person gandalf = ldapTestsSetup.getUser("userA");
    Group others = ldapTestsSetup.getGroup("groupD");
    String krbPrincipalName = gandalf.getUsername() + "@" + gandalf.getDomain();
    LdapSearchByUserNameParameters adParameters = new LdapSearchByUserNameParameters(null, dnToDomain(ldapCtx.getBaseLdapPathAsString()), gandalf.getUsername());
    LdapGetAdUserByUserNameCommand command = new LdapGetAdUserByUserNameCommand(adParameters);
    LdapReturnValueBase retVal = command.Execute();
    assertNotNull(retVal);
    assertTrue(retVal.getSucceeded());
    AdUser adUser = (AdUser) retVal.getReturnValue();
    assertNotNull(adUser);
    assertEquals(krbPrincipalName, adUser.getUserName());
    assertEquals(gandalf.getGivenName(), adUser.getName());
    List<String> memberOf = adUser.getMemberof();
    assertTrue(memberOf.get(0).contains(others.getName()));
    assertEquals(gandalf.getSurName(), adUser.getSurName());
    // no results
    LdapSearchByUserNameParameters adParametersNoResults = new LdapSearchByUserNameParameters(null, dnToDomain(ldapCtx.getBaseLdapPathAsString()), gandalf.getUsername() + "blabla");
    LdapGetAdUserByUserNameCommand commandNoResults = new LdapGetAdUserByUserNameCommand(adParametersNoResults);
    LdapReturnValueBase retValNoResults = commandNoResults.Execute();
    assertNotNull(retValNoResults);
    assertTrue(!retValNoResults.getSucceeded());
    // illegal domain
    LdapSearchByUserNameParameters adParametersIllegalDomain = new LdapSearchByUserNameParameters(null, dnToDomain("blabla." + ldapCtx.getBaseLdapPathAsString()), gandalf.getUsername());
    LdapGetAdUserByUserNameCommand commandIllegalDomain = new LdapGetAdUserByUserNameCommand(adParametersIllegalDomain);
    LdapReturnValueBase retValIllegalDomain = commandIllegalDomain.Execute();
    assertNotNull(retValIllegalDomain);
    assertTrue(!retValIllegalDomain.getSucceeded());
}
Example 6
Project: spring-boot-master  File: EmbeddedLdapAutoConfiguration.java View source code
@Bean
@DependsOn("directoryServer")
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
    LdapContextSource source = new LdapContextSource();
    if (hasCredentials(this.embeddedProperties.getCredential())) {
        source.setUserDn(this.embeddedProperties.getCredential().getUsername());
        source.setPassword(this.embeddedProperties.getCredential().getPassword());
    }
    source.setUrls(this.properties.determineUrls(this.environment));
    return source;
}
Example 7
Project: spring-ldap-master  File: LdapTemplateNamespaceHandlerTest.java View source code
@Test
public void verifyThatAnonymousReadOnlyContextWillNotBeWrappedInProxy() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-anonymous-read-only.xml");
    ContextSource contextSource = ctx.getBean(ContextSource.class);
    assertThat(contextSource).isNotNull();
    assertThat(contextSource instanceof LdapContextSource).isTrue();
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly"));
}
Example 8
Project: zstack-master  File: LdapUtil.java View source code
void setTls(LdapContextSource ldapContextSource) {
    // set tls
    logger.debug("Ldap TLS enabled.");
    DefaultTlsDirContextAuthenticationStrategy tls = new DefaultTlsDirContextAuthenticationStrategy();
    tls.setHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    tls.setSslSocketFactory(new DummySSLSocketFactory());
    ldapContextSource.setAuthenticationStrategy(tls);
}
Example 9
Project: elpaaso-core-master  File: LdapContext.java View source code
//	<bean id="sdContextSourceTarget" class="org.springframework.ldap.core.support.LdapContextSource">
//	<property name="url" value="${ldap.url}" />
//	<property name="userDn" value="${ldap.manager_dn}" />
//	<property name="password" value="${ldap.manager_password}" />
//	<property name="pooled" value="false" />
//	</bean>
@Bean
public LdapContextSource sdContextSourceTarget() {
    LdapContextSource ldapContextSource = new LdapContextSource();
    ldapContextSource.setUrl(ldapUrl);
    ldapContextSource.setUserDn(managerUserDn);
    ldapContextSource.setPassword(managerPasword);
    ldapContextSource.setPooled(false);
    ldapContextSource.afterPropertiesSet();
    return ldapContextSource;
}
Example 10
Project: geoserver-master  File: LDAPTestUtils.java View source code
/**
     * Initializes an in-memory LDAP server to use for testing.
     * 
     * @param allowAnonymous
     *            anonymous access is allowed or not
     */
public static boolean initLdapServer(boolean allowAnonymous, String ldapServerUrl, String basePath, String ldifPath) throws Exception {
    try {
        if (!portIsBusy("127.0.0.1", LDAP_SERVER_PORT)) {
            startEmbeddedServer(LDAP_SERVER_PORT, basePath, "test", allowAnonymous);
            // Bind to the directory
            LdapContextSource contextSource = new LdapContextSource();
            contextSource.setUrl(ldapServerUrl);
            contextSource.setUserDn(DEFAULT_PRINCIPAL);
            contextSource.setPassword(DEFAULT_PASSWORD);
            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
            cleanAndSetup(template.getContextSource(), new DistinguishedName("dc=example,dc=com"), new ClassPathResource(ldifPath));
            return true;
        }
        return false;
    } catch (Exception ee) {
        return false;
    }
}
Example 11
Project: cmestemp22-master  File: SearchStringLdapTemplateRetriever.java View source code
/**
     * Uses specified search string and/or template key to return an LdapTemplate used to make query. If search string
     * contains domain, that is used to try to find LdapTemplate, if not, template key is used to attempt to find it, if
     * neither is present or results in a LdapTemplate being found, default template is used.
     * 
     * @param inLdapLookupRequest
     *            {@link LdapLookupRequest}.
     * @return {@link LdapTemplate} based on {@link LdapLookupRequest}, or default if none found.
     */
@Override
protected LdapTemplate retrieveLdapTemplate(final LdapLookupRequest inLdapLookupRequest) {
    String templateKey = inLdapLookupRequest.getTemplateKey();
    String searchString = inLdapLookupRequest.getQueryString();
    LdapTemplate result = null;
    if (searchString != null && searchString.contains("\\")) {
        String[] domainQueryArr = searchString.split("\\\\");
        // Example: "domain\attribute=foo" will give domain of "domain" and searchString of "attribute=foo".
        String domain = domainQueryArr[0];
        searchString = domainQueryArr[1];
        // no matter what domain we get, modify search string to remove domain.
        inLdapLookupRequest.setQueryString(searchString);
        // if domain is not null/empty, try to use it for ldap template.
        if (domain != null && !domain.isEmpty()) {
            result = getLdapTemplates().get(domain);
        }
        // no dice on domain from search string, try template key.
        if (result == null && templateKey != null) {
            result = getLdapTemplates().get(templateKey);
        }
        // if not found, give back default, but log as error.
        if (result == null) {
            result = getDefaultLdapTemplate();
            log.error("Domain specified (" + domain + "), but not found in list of templates. " + "Attempting search on default template");
        }
        if (log.isDebugEnabled()) {
            log.debug("Domain specified, searching only on " + ((LdapContextSource) result.getContextSource()).getUrls()[0] + " for : " + searchString);
        }
    } else {
        // no domain specified in search string, try template key.
        if (templateKey != null) {
            result = getLdapTemplates().get(templateKey);
        }
        // no dice with template key, use default.
        if (result == null) {
            result = getDefaultLdapTemplate();
        }
        if (log.isDebugEnabled()) {
            log.debug("No domain specified, searching only on " + ((LdapContextSource) result.getContextSource()).getUrls()[0] + " for : " + searchString);
        }
    }
    return result;
}
Example 12
Project: eurekastreams-master  File: SearchStringLdapTemplateRetriever.java View source code
/**
     * Uses specified search string and/or template key to return an LdapTemplate used to make query. If search string
     * contains domain, that is used to try to find LdapTemplate, if not, template key is used to attempt to find it, if
     * neither is present or results in a LdapTemplate being found, default template is used.
     * 
     * @param inLdapLookupRequest
     *            {@link LdapLookupRequest}.
     * @return {@link LdapTemplate} based on {@link LdapLookupRequest}, or default if none found.
     */
@Override
protected LdapTemplate retrieveLdapTemplate(final LdapLookupRequest inLdapLookupRequest) {
    String templateKey = inLdapLookupRequest.getTemplateKey();
    String searchString = inLdapLookupRequest.getQueryString();
    LdapTemplate result = null;
    if (searchString != null && searchString.contains("\\")) {
        String[] domainQueryArr = searchString.split("\\\\");
        // Example: "domain\attribute=foo" will give domain of "domain" and searchString of "attribute=foo".
        String domain = domainQueryArr[0].toLowerCase();
        searchString = domainQueryArr[1];
        // no matter what domain we get, modify search string to remove domain.
        inLdapLookupRequest.setQueryString(searchString);
        // if domain is not null/empty, try to use it for ldap template.
        if (domain != null && !domain.isEmpty()) {
            result = getLdapTemplates().get(domain);
        }
        // no dice on domain from search string, try template key.
        if (result == null && templateKey != null) {
            result = getLdapTemplates().get(templateKey);
        }
        // if not found, give back default, but log as error.
        if (result == null) {
            result = getDefaultLdapTemplate();
            log.error("Domain specified (" + domain + "), but not found in list of templates. " + "Attempting search on default template");
        }
        if (log.isDebugEnabled()) {
            log.debug("Domain specified, searching only on " + ((LdapContextSource) result.getContextSource()).getUrls()[0] + " with base: " + ((LdapContextSource) result.getContextSource()).getBaseLdapPathAsString() + " for : " + searchString);
        }
    } else {
        // no domain specified in search string, try template key.
        if (templateKey != null) {
            result = getLdapTemplates().get(templateKey);
        }
        // no dice with template key, use default.
        if (result == null) {
            result = getDefaultLdapTemplate();
        }
        if (log.isDebugEnabled()) {
            log.debug("No domain specified, searching only on " + ((LdapContextSource) result.getContextSource()).getUrls()[0] + " for : " + searchString);
        }
    }
    return result;
}
Example 13
Project: geofence-master  File: BaseDAOTest.java View source code
@Before
public void setUp() throws Exception {
    org.junit.Assume.assumeNotNull(ldapContext);
    // Bind to the directory
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:10389");
    contextSource.setUserDn(LdapTestUtils.DEFAULT_PRINCIPAL);
    contextSource.setPassword(LdapTestUtils.DEFAULT_PASSWORD);
    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.cleanAndSetup(template.getContextSource(), new DistinguishedName("dc=example,dc=com"), new ClassPathResource("data.ldif"));
    LOGGER.info("################ Running " + getClass().getSimpleName());
    LOGGER.info("##### Ending setup for " + getClass().getSimpleName() + " ###----------------------");
}
Example 14
Project: InSpider-master  File: BaseLdapManagerDaoTest.java View source code
@Before
@Override
public void buildDB() throws Exception {
    super.buildDB();
    // Bind to the LDAP directory:
    final LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://127.0.0.1:" + PORT + "/dc=inspire,dc=idgis,dc=eu");
    contextSource.setUserDn(PRINCIPAL);
    contextSource.setPassword(CREDENTIALS);
    contextSource.setPooled(false);
    contextSource.afterPropertiesSet();
    // Create an LDAP template:
    ldapTemplate = new LdapTemplate(contextSource);
    LdapTestUtils.cleanAndSetup(ldapTemplate.getContextSource(), new DistinguishedName(), new ClassPathResource("nl/ipo/cds/dao/testdata.ldif"));
    ((ManagerDaoImpl) managerDao).setLdapTemplate(ldapTemplate);
    entityManager.flush();
}
Example 15
Project: person-directory-master  File: AbstractDirContextTest.java View source code
/**
     * Initialize the server.
     */
@Override
public final void setUp() throws Exception {
    final String partitionName = this.getPartitionName();
    // Add partition 'sevenSeas'
    final MutablePartitionConfiguration partitionConfiguration = new MutablePartitionConfiguration();
    partitionConfiguration.setName(partitionName);
    partitionConfiguration.setSuffix("o=" + partitionName);
    // Create some indices
    final Set<Object> indexedAttrs = new HashSet<>();
    indexedAttrs.add("objectClass");
    indexedAttrs.add("o");
    partitionConfiguration.setIndexedAttributes(indexedAttrs);
    // Create a first entry associated to the partition
    final Attributes attrs = new BasicAttributes(true);
    // First, the objectClass attribute
    final Attribute objectClassAttr = new BasicAttribute("objectClass");
    objectClassAttr.add("top");
    objectClassAttr.add("organization");
    attrs.put(objectClassAttr);
    // The the 'Organization' attribute
    final Attribute orgAttribute = new BasicAttribute("o");
    orgAttribute.add(partitionName);
    attrs.put(orgAttribute);
    // Associate this entry to the partition
    partitionConfiguration.setContextEntry(attrs);
    // As we can create more than one partition, we must store
    // each created partition in a Set before initialization
    final Set<MutablePartitionConfiguration> partitionConfigurations = new HashSet<>();
    partitionConfigurations.add(partitionConfiguration);
    this.configuration.setContextPartitionConfigurations(partitionConfigurations);
    // Create a working directory
    final File workingDirectory = File.createTempFile(this.getClass().getName() + ".", ".apacheds-server-work");
    workingDirectory.delete();
    workingDirectory.deleteOnExit();
    this.configuration.setWorkingDirectory(workingDirectory);
    // Now, let's call the upper class which is responsible for the
    // partitions creation
    super.setUp();
    // Load initializating ldif data
    final Resource[] initializationData = this.initializationData();
    for (final Resource data : initializationData) {
        final InputStream dataStream = data.getInputStream();
        this.importLdif(dataStream);
    }
    //Setup the ContextSource
    final DirContext context = this.createContext();
    this.contextSource = new SingleContextSource(context);
    this.contextSource = new LdapContextSource();
    ((LdapContextSource) this.contextSource).setUrl("ldap://localhost:" + this.port);
    ((LdapContextSource) this.contextSource).setBase(this.getBaseDn());
    ((LdapContextSource) this.contextSource).afterPropertiesSet();
    this.internalSetUp();
}
Example 16
Project: ambari-master  File: AmbariLdapDataPopulatorTest.java View source code
@Test
public void testReferralMethod() {
    final Configuration configuration = createNiceMock(Configuration.class);
    final Users users = createNiceMock(Users.class);
    LdapContextSource ldapContextSource = createNiceMock(LdapContextSource.class);
    List<String> ldapUrls = Collections.singletonList("url");
    LdapTemplate ldapTemplate = createNiceMock(LdapTemplate.class);
    LdapServerProperties ldapServerProperties = createNiceMock(LdapServerProperties.class);
    expect(configuration.getLdapServerProperties()).andReturn(ldapServerProperties).anyTimes();
    expect(ldapServerProperties.getLdapUrls()).andReturn(ldapUrls).anyTimes();
    expect(ldapServerProperties.getReferralMethod()).andReturn("follow");
    ldapContextSource.setReferral("follow");
    ldapTemplate.setIgnorePartialResultException(true);
    replay(ldapTemplate, configuration, ldapServerProperties, ldapContextSource);
    final TestAmbariLdapDataPopulator populator = new TestAmbariLdapDataPopulator(configuration, users);
    populator.setLdapContextSource(ldapContextSource);
    populator.setLdapTemplate(ldapTemplate);
    populator.setLdapServerProperties(ldapServerProperties);
    populator.loadLdapTemplate();
    verify(ldapTemplate, configuration, ldapServerProperties, ldapContextSource);
}
Example 17
Project: coprhd-controller-master  File: ImmutableAuthenticationProviders.java View source code
private static ArrayList<LdapContextSource> createLDAPContextSources(CoordinatorClient coordinator, final AuthnProvider authenticationConfiguration, final Map<String, String> environmentProperties) {
    ArrayList<LdapContextSource> ctxSources = new ArrayList<>();
    for (String url : authenticationConfiguration.getServerUrls()) {
        LdapContextSource ctx = createLDAPContextSource(coordinator, authenticationConfiguration, environmentProperties, url);
        ctxSources.add(ctx);
    }
    return ctxSources;
}
Example 18
Project: kylo-master  File: LdapAuthConfig.java View source code
@Override
protected LdapContextSource createInstance() throws Exception {
    DefaultSpringSecurityContextSource cxt = new DefaultSpringSecurityContextSource(this.uri.toASCIIString());
    if (StringUtils.isNotEmpty(this.authDn)) {
        cxt.setUserDn(this.authDn);
    }
    if (ArrayUtils.isNotEmpty(this.password)) {
        cxt.setPassword(new String(this.password));
    }
    cxt.setCacheEnvironmentProperties(false);
    cxt.afterPropertiesSet();
    return cxt;
}
Example 19
Project: incubator-atlas-master  File: AtlasLdapAuthenticationProvider.java View source code
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;
}
Example 20
Project: openmicroscopy-master  File: LdapTest.java View source code
protected Fixture createFixture(File ctxFile) throws Exception {
    Fixture fixture = new Fixture();
    fixture.ctx = new FileSystemXmlApplicationContext("file:" + ctxFile.getAbsolutePath());
    fixture.config = (LdapConfig) fixture.ctx.getBean("config");
    Map<String, LdapContextSource> sources = fixture.ctx.getBeansOfType(LdapContextSource.class);
    LdapContextSource source = sources.values().iterator().next();
    String[] urls = source.getUrls();
    assertEquals(1, urls.length);
    fixture.template = new LdapTemplate(source);
    fixture.role = mock(RoleProvider.class);
    RoleProvider provider = (RoleProvider) fixture.role.proxy();
    fixture.sql = mock(SqlAction.class);
    SqlAction sql = (SqlAction) fixture.sql.proxy();
    fixture.queryMock = mock(LocalQuery.class);
    fixture.query = (LocalQuery) fixture.queryMock.proxy();
    fixture.queryMock.expects(once()).method("findByString").will(returnValue(null));
    fixture.ldap = new LdapImpl(source, fixture.template, new Roles(), fixture.config, provider, sql);
    fixture.ldap.setQueryService(fixture.query);
    fixture.provider = new LdapPasswordProvider(new PasswordUtil(sql), fixture.ldap);
    return fixture;
}
Example 21
Project: ranger-master  File: RangerAuthenticationProvider.java View source code
private Authentication getLdapAuthentication(Authentication authentication) {
    try {
        // getting ldap settings
        String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", "");
        String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", "");
        String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", "");
        String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", "");
        String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", "");
        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
        // 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(rangerLdapURL);
        ldapContextSource.setCacheEnvironmentProperties(false);
        ldapContextSource.setAnonymousReadOnly(true);
        // Creating BindAuthenticator using Ldap Context Source.
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern };
        String[] userDnPatterns = rangerLdapUserDNPattern.split(";");
        bindAuthenticator.setUserDnPatterns(userDnPatterns);
        LdapAuthenticationProvider ldapAuthenticationProvider = null;
        if (!StringUtil.isEmpty(rangerLdapGroupSearchBase) && !StringUtil.isEmpty(rangerLdapGroupSearchFilter)) {
            // 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, rangerLdapGroupSearchBase);
            defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute);
            defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter);
            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 = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            authentication = getAuthenticationWithGrantedAuthority(authentication);
            return authentication;
        } else {
            return authentication;
        }
    } catch (Exception e) {
        logger.debug("LDAP Authentication Failed:", e);
    }
    return authentication;
}
Example 22
Project: LDAP-provider-master  File: LdapProviderConfiguration.java View source code
private boolean testConnection(String url, String bindDn, String bindPassword) throws Exception {
    if (StringUtils.isBlank(url)) {
        return false;
    }
    LdapContextSource lcs = new LdapContextSource();
    lcs.setUrl(url);
    if (StringUtils.isNotBlank(bindDn)) {
        lcs.setUserDn(bindDn);
    }
    if (StringUtils.isNotBlank(bindPassword)) {
        lcs.setPassword(bindPassword);
    }
    try {
        lcs.afterPropertiesSet();
        lcs.getReadOnlyContext();
    } catch (Exception e) {
        throw getRootCause(e);
    }
    return true;
}
Example 23
Project: linshare-core-master  File: JScriptLdapQuery.java View source code
/**
	 * Ldap Authentification method
	 * 
	 * @param login
	 * @param userPasswd
	 * @return
	 * @throws NamingException
	 */
public User auth(LdapConnection ldapConnection, String login, String userPasswd) throws NamingException {
    String command = domainPattern.getAuthCommand();
    Map<String, Object> vars = lqlctx.getVariables();
    vars.put("login", cleanLdapInputPattern(login));
    if (logger.isDebugEnabled())
        logLqlQuery(command, login);
    // searching ldap directory with pattern
    // InvalidSearchFilterException
    List<String> dnResultList = this.evaluate(command);
    if (dnResultList == null || dnResultList.size() < 1) {
        throw new NameNotFoundException("No user found for login: " + login);
    } else if (dnResultList.size() > 1) {
        logger.error("The authentification query had returned more than one user !!!");
        return null;
    }
    LdapContextSource ldapContextSource = new LdapContextSource();
    ldapContextSource.setUrl(ldapConnection.getProviderUrl());
    String securityPrincipal = ldapConnection.getSecurityPrincipal();
    if (securityPrincipal != null) {
        ldapContextSource.setUserDn(securityPrincipal);
    }
    String securityCredentials = ldapConnection.getSecurityCredentials();
    if (securityCredentials != null) {
        ldapContextSource.setPassword(securityCredentials);
    }
    String userDn = dnResultList.get(0);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDn, userPasswd);
    BindAuthenticator authenticator = new BindAuthenticator(ldapContextSource);
    String searchFilter = "(objectClass=*)";
    String localBaseDn = userDn + "," + baseDn;
    LdapUserSearch userSearch = new FilterBasedLdapUserSearch(localBaseDn, searchFilter, ldapContextSource);
    authenticator.setUserSearch(userSearch);
    try {
        ldapContextSource.afterPropertiesSet();
        authenticator.authenticate(authentication);
    } catch (BadCredentialsException e) {
        logger.debug("auth failed : BadCredentialsException(" + userDn + ")");
        throw e;
    } catch (Exception e) {
        logger.error("auth failed for unexpected exception: " + e.getMessage(), e);
        throw e;
    }
    return dnToUser(userDn, false);
}
Example 24
Project: arsnova-backend-master  File: SecurityConfig.java View source code
@Bean
public LdapContextSource ldapContextSource() {
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(ldapUrl);
    /* TODO: implement support for LDAP bind using manager credentials */
    if (!"".equals(ldapManagerUserDn) && !"".equals(ldapManagerPassword)) {
        logger.debug("ldapManagerUserDn: {}", ldapManagerUserDn);
        contextSource.setUserDn(ldapManagerUserDn);
        contextSource.setPassword(ldapManagerPassword);
    }
    return contextSource;
}
Example 25
Project: HERD-master  File: DaoSpringModuleConfig.java View source code
/**
     * Gets an LDAP context source.
     *
     * @return the LDAP context source
     */
@Bean
public LdapContextSource contextSource() {
    String ldapUrl = configurationHelper.getProperty(ConfigurationValue.LDAP_URL);
    String ldapBase = configurationHelper.getProperty(ConfigurationValue.LDAP_BASE);
    String ldapUserDn = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN);
    LOGGER.info("Creating LDAP context source using the following parameters: {}=\"{}\" {}=\"{}\" {}=\"{}\" ...", ConfigurationValue.LDAP_URL.getKey(), ldapUrl, ConfigurationValue.LDAP_BASE.getKey(), ldapBase, ConfigurationValue.LDAP_USER_DN.getKey(), ldapUserDn);
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUserDn);
    contextSource.setPassword(configurationHelper.getProperty(ConfigurationValue.LDAP_PASSWORD));
    return contextSource;
}
Example 26
Project: nifi-master  File: LdapProvider.java View source code
@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.");
    }
    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);
}
Example 27
Project: libreplan-master  File: ConfigurationController.java View source code
/**
     * Used in configuration.zul
     * Should be public!
     */
public void testLDAPConnection() {
    LdapContextSource source = new LdapContextSource();
    source.setUrl(configurationModel.getLdapConfiguration().getLdapHost() + ":" + configurationModel.getLdapConfiguration().getLdapPort());
    source.setBase(configurationModel.getLdapConfiguration().getLdapBase());
    source.setUserDn(configurationModel.getLdapConfiguration().getLdapUserDn());
    source.setPassword(configurationModel.getLdapConfiguration().getLdapPassword());
    source.setDirObjectFactory(DefaultDirObjectFactory.class);
    source.setPooled(false);
    try {
        source.afterPropertiesSet();
    } catch (Exception e) {
        e.printStackTrace();
    }
    LdapTemplate template = new LdapTemplate(source);
    try {
        /* TODO resolve deprecated */
        template.authenticate(DistinguishedName.EMPTY_PATH, new EqualsFilter(configurationModel.getLdapConfiguration().getLdapUserId(), "test").toString(), "test");
        messages.showMessage(Level.INFO, _("LDAP connection was successful"));
    } catch (Exception e) {
        LOG.info(e);
        messages.showMessage(Level.ERROR, _("Cannot connect to LDAP server"));
    }
}
Example 28
Project: spring-security-master  File: ApacheDSEmbeddedLdifTests.java View source code
private LdapContextSource createLdapContextSource() throws Exception {
    LdapContextSource ldapContextSource = new LdapContextSource();
    ldapContextSource.setUrl("ldap://localhost:" + LDAP_PORT);
    ldapContextSource.setBase(LDAP_ROOT);
    ldapContextSource.afterPropertiesSet();
    return ldapContextSource;
}