Java Code Examples for org.springframework.ldap.core.support.LdapContextSource#afterPropertiesSet()

The following examples show how to use org.springframework.ldap.core.support.LdapContextSource#afterPropertiesSet() . 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 File: LdapLoginProvider.java    From cuba with Apache License 2.0 7 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 2
Source File: LdapCredentialsAuthenticator.java    From ob1k with 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 3
Source File: BaseDAOTest.java    From geofence with 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 4
Source File: AuthenticationCheck.java    From ranger with Apache License 2.0 6 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 5
Source File: LDAPIdentityServiceImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@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 6
Source File: LdapManager.java    From blackduck-alert with 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 7
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
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 8
Source File: TestLdap.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private static ContextSource getContextSource(String url, String username, String password) throws Exception {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(url);
    contextSource.setUserDn(username);
    contextSource.setPassword(password);
    contextSource.setPooled(false);
    contextSource.afterPropertiesSet();

    return contextSource;
}
 
Example 9
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 5 votes vote down vote up
private Authentication getADBindAuthentication(Authentication authentication) {
	try {
		String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", "");
		String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", "");
		String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", "");
		String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", "");
		String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
		String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow");
		String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})");
		boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty(
				"ranger.ldap.starttls", "false"));
		String userName = authentication.getName();
		String userPassword = "";
		if (authentication.getCredentials() != null) {
			userPassword = authentication.getCredentials().toString();
		}

		LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL);
		ldapContextSource.setUserDn(rangerADBindDN);
		ldapContextSource.setPassword(rangerADBindPassword);
		ldapContextSource.setReferral(rangerLdapReferral);
		ldapContextSource.setCacheEnvironmentProperties(true);
		ldapContextSource.setAnonymousReadOnly(false);
		ldapContextSource.setPooled(true);
		if (rangerIsStartTlsEnabled) {
			ldapContextSource.setPooled(false);
			ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy());
		}
		ldapContextSource.afterPropertiesSet();

		//String searchFilter="(sAMAccountName={0})";
		if (rangerLdapUserSearchFilter==null || rangerLdapUserSearchFilter.trim().isEmpty()) {
			rangerLdapUserSearchFilter="(sAMAccountName={0})";
		}
		FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter,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(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("AD Authentication Failed:", e);
	}
	return authentication;
}
 
Example 10
Source File: LdapConfig.java    From metron with 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 11
Source File: TestContextSourceFactoryBean.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
protected ContextSource createInstance() throws Exception {
    LdapTestUtils.startEmbeddedServer(port,
            defaultPartitionSuffix, defaultPartitionName);

    if (contextSource == null) {
        // If not explicitly configured, create a new instance.
        LdapContextSource targetContextSource = new LdapContextSource();
        if (baseOnTarget) {
            targetContextSource.setBase(defaultPartitionSuffix);
        }

        targetContextSource.setUrl("ldap://localhost:" + port);
        targetContextSource.setUserDn(principal);
        targetContextSource.setPassword(password);
        targetContextSource.setDirObjectFactory(dirObjectFactory);
        targetContextSource.setPooled(pooled);

        if (authenticationSource != null) {
            targetContextSource.setAuthenticationSource(authenticationSource);
        }
        targetContextSource.afterPropertiesSet();

        contextSource = targetContextSource;
    }

    Thread.sleep(1000);

    if (baseOnTarget) {
        LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName());
    }
    else {
        LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName(defaultPartitionSuffix));
    }

    if (ldifFile != null) {
        LdapTestUtils.loadLdif(contextSource, ldifFile);
    }

    return contextSource;
}
 
Example 12
Source File: TestContextSourceFactoryBean.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
protected Object createInstance() throws Exception {
       LdapTestUtils.startEmbeddedServer(port, defaultPartitionSuffix, defaultPartitionName);

       if (contextSource == null) {
           // If not explicitly configured, create a new instance.
           LdapContextSource targetContextSource = new LdapContextSource();
           if (baseOnTarget) {
               targetContextSource.setBase(defaultPartitionSuffix);
           }

           targetContextSource.setUrl("ldap://localhost:" + port);
           targetContextSource.setUserDn(principal);
           targetContextSource.setPassword(password);
           targetContextSource.setDirObjectFactory(dirObjectFactory);
           targetContextSource.setPooled(pooled);

           if (authenticationSource != null) {
               targetContextSource.setAuthenticationSource(authenticationSource);
           }
           targetContextSource.afterPropertiesSet();

           contextSource = targetContextSource;
       }

       Thread.sleep(1000);

       if (baseOnTarget) {
		LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName());
	}
	else {
		LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName(defaultPartitionSuffix));
	}

	if (ldifFile != null) {
           LdapTestUtils.loadLdif(contextSource, ldifFile);
	}

	return contextSource;
}
 
Example 13
Source File: AtlasLdapAuthenticationProvider.java    From atlas with 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 14
Source File: TestSchemaToJava.java    From spring-ldap with 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"));
}
 
Example 15
Source File: ContextSourceEc2InstanceLaunchingFactoryBean.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Override
protected final Object doCreateInstance(final String dnsName) throws Exception {
	Assert.hasText(userDn);
	LdapContextSource instance = new LdapContextSource();
	instance.setUrl("ldap://" + dnsName);
	instance.setUserDn(userDn);
	instance.setPassword(password);
	instance.setBase(base);
	instance.setPooled(pooled);
	setAdditionalContextSourceProperties(instance, dnsName);

	instance.afterPropertiesSet();
	return instance;
}
 
Example 16
Source File: AtlasADAuthenticationProvider.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
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();

         if (adUserSearchFilter==null || adUserSearchFilter.trim().isEmpty()) {
             adUserSearchFilter="(sAMAccountName={0})";
         }
         FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adBase, adUserSearchFilter,ldapContextSource);
         userSearch.setSearchSubtree(true);

         BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
         bindAuthenticator.setUserSearch(userSearch);
         bindAuthenticator.afterPropertiesSet();

LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

         if (userName != null && userPassword != null
                 && !userName.trim().isEmpty()
                 && !userPassword.trim().isEmpty()) {
             final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
             final UserDetails principal = new User(userName, userPassword,
                     grantedAuths);
             final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                     principal, userPassword, grantedAuths);
             authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
             if (groupsFromUGI) {
                 authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
             }
             return authentication;
         } else {
             LOG.error("AD Authentication Failed userName or userPassword is null or empty");
             return null;
         }
     } catch (Exception e) {
         LOG.error("AD Authentication Failed:", e);
         return null;
     }
 }
 
Example 17
Source File: SubjectMatterExpertDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public SubjectMatterExpertContactDetails getSubjectMatterExpertByKey(SubjectMatterExpertKey subjectMatterExpertKey)
{
    // Get LDAP specific configuration settings.
    final String ldapUrl = configurationHelper.getProperty(ConfigurationValue.LDAP_URL);
    final String ldapBase = configurationHelper.getProperty(ConfigurationValue.LDAP_BASE);
    final String ldapUserDn = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN);
    final String credStashEncryptionContext = configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    final String ldapUserCredentialName = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);

    // Log configuration values being used to create LDAP context source.
    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, ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT.getKey(), credStashEncryptionContext,
        ConfigurationValue.LDAP_USER_CREDENTIAL_NAME.getKey(), ldapUserCredentialName);

    // Retrieve LDAP user password from the credstash.
    String ldapUserPassword;
    try
    {
        ldapUserPassword = credStashHelper.getCredentialFromCredStash(credStashEncryptionContext, ldapUserCredentialName);
    }
    catch (CredStashGetCredentialFailedException e)
    {
        throw new IllegalStateException(e);
    }

    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUserDn);
    contextSource.setPassword(ldapUserPassword);
    contextSource.afterPropertiesSet();

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

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).is(subjectMatterExpertKey.getUserId());

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

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

    // Return the results.
    return CollectionUtils.isNotEmpty(subjectMatterExpertContactDetailsList) ? subjectMatterExpertContactDetailsList.get(0) : null;
}
 
Example 18
Source File: AtlasADAuthenticationProvider.java    From atlas with Apache License 2.0 4 votes vote down vote up
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;
     }
 }
 
Example 19
Source File: AuthenticationCheck.java    From ranger with Apache License 2.0 4 votes vote down vote up
private Authentication getLdapBindAuthentication(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(false);
        ldapContextSource.setAnonymousReadOnly(true);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, groupSearchBase);
        defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(roleAttribute);
        defaultLdapAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
        defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);

        String searchFilter="(uid={0})";
        FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adDomain, searchFilter,ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        String[] userDnPatterns = new String[] { userDnPattern };
        bindAuthenticator.setUserDnPatterns(userDnPatterns);
        bindAuthenticator.afterPropertiesSet();

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator,defaultLdapAuthoritiesPopulator);

        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 20
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 4 votes vote down vote up
private boolean ldapAuthentication(Long organizationId, String loginName, String credentials) {
    LdapE ldap = ldapService.queryByOrgId(organizationId);
    if (ldap != null && ldap.getEnabled()) {
        LdapContextSource contextSource = new LdapContextSource();
        String url = ldap.getServerAddress() + ":" + ldap.getPort();
        int connectionTimeout = ldap.getConnectionTimeout();
        contextSource.setUrl(url);
        contextSource.setBase(ldap.getBaseDn());
        setConnectionTimeout(contextSource, connectionTimeout);
        contextSource.afterPropertiesSet();

        LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        //ad目录不设置会报错
        if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
            ldapTemplate.setIgnorePartialResultException(true);
        }
        String userDn = null;
        boolean anonymousFetchFailed = false;

        AndFilter filter = getLoginFilter(ldap, loginName);
        try {
            List<String> names =
                    ldapTemplate.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) {
            anonymousFetchFailed = true;
            LOG.error("ldap anonymous search failed, filter {}, exception {}", filter, e);
        }
        if (anonymousFetchFailed) {
            userDn = accountAsUserDn2Authentication(loginName, ldap, contextSource, filter);
        }
        if (userDn == null) {
            LOG.error("can not get userDn by filter {}, login failed", filter);
            return false;
        }
        return authentication(credentials, contextSource, userDn);
    } else {
        throw new AuthenticationServiceException(LoginException.LDAP_IS_DISABLE.value());
    }
}