org.springframework.security.ldap.authentication.LdapAuthenticationProvider Java Examples

The following examples show how to use org.springframework.security.ldap.authentication.LdapAuthenticationProvider. 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: 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 #2
Source File: LdapAuthenticationProviderConfigurer.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private LdapAuthenticationProvider build() throws Exception {
    BaseLdapPathContextSource contextSource = getContextSource();
    LdapAuthenticator ldapAuthenticator = createLdapAuthenticator(contextSource);

    LdapAuthoritiesPopulator authoritiesPopulator = getLdapAuthoritiesPopulator();

    LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProviderProxy(
            ldapAuthenticator, authoritiesPopulator);
    SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
    simpleAuthorityMapper.setPrefix(rolePrefix);
    simpleAuthorityMapper.afterPropertiesSet();
    ldapAuthenticationProvider.setAuthoritiesMapper(simpleAuthorityMapper);
    if (userDetailsContextMapper != null) {
        ldapAuthenticationProvider
                .setUserDetailsContextMapper(userDetailsContextMapper);
    }
    return ldapAuthenticationProvider;
}
 
Example #3
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 #4
Source File: AuthenticationTestAction.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
private void performLdapTest(FieldModel fieldModel, FieldAccessor registeredFieldValues) throws IntegrationException {
    logger.info("LDAP enabled testing LDAP authentication.");
    String userName = fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_USERNAME).orElse("");
    Optional<LdapAuthenticationProvider> ldapProvider = ldapManager.createAuthProvider(registeredFieldValues);
    String errorMessage = String.format("Ldap Authentication test failed for the test user %s.  Please check the LDAP configuration.", userName);
    Map<String, String> errorsMap = new HashMap<>();
    if (!ldapProvider.isPresent()) {
        errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
    } else {
        Authentication pendingAuthentication = new UsernamePasswordAuthenticationToken(userName,
            fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_PASSWORD).orElse(""));
        Authentication authentication = ldapProvider.get().authenticate(pendingAuthentication);
        if (!authentication.isAuthenticated()) {
            errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
        }
        authentication.setAuthenticated(false);
    }

    if (!errorsMap.isEmpty()) {
        throw new AlertFieldException(errorsMap);
    }
}
 
Example #5
Source File: LoginActionsTestIT.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationLDAPExceptionIT() throws Exception {
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.isAuthenticated()).thenReturn(true);
    LdapAuthenticationProvider ldapAuthenticationProvider = Mockito.mock(LdapAuthenticationProvider.class);
    Mockito.when(ldapAuthenticationProvider.authenticate(Mockito.any(Authentication.class))).thenReturn(authentication);
    LdapManager mockLdapManager = Mockito.mock(LdapManager.class);
    Mockito.when(mockLdapManager.isLdapEnabled()).thenReturn(true);
    Mockito.when(mockLdapManager.getAuthenticationProvider()).thenThrow(new AlertConfigurationException("LDAP CONFIG EXCEPTION"));
    DaoAuthenticationProvider databaseProvider = Mockito.mock(DaoAuthenticationProvider.class);
    Mockito.when(databaseProvider.authenticate(Mockito.any(Authentication.class))).thenReturn(authentication);
    AuthenticationEventManager authenticationEventManager = Mockito.mock(AuthenticationEventManager.class);
    Mockito.doNothing().when(authenticationEventManager).sendAuthenticationEvent(Mockito.any(), Mockito.eq(AuthenticationType.LDAP));
    AuthorizationUtility authorizationUtility = Mockito.mock(AuthorizationUtility.class);

    AlertDatabaseAuthenticationPerformer alertDatabaseAuthenticationPerformer = new AlertDatabaseAuthenticationPerformer(authenticationEventManager, authorizationUtility, databaseProvider);

    AlertAuthenticationProvider authenticationProvider = new AlertAuthenticationProvider(List.of(alertDatabaseAuthenticationPerformer));
    LoginActions loginActions = new LoginActions(authenticationProvider);
    boolean authenticated = loginActions.authenticateUser(mockLoginRestModel.createRestModel());
    assertFalse(authenticated);
    Mockito.verify(databaseProvider).authenticate(Mockito.any(Authentication.class));
}
 
Example #6
Source File: LdapSecurityConfiguration.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter(LdapAuthenticationProvider authenticationProvider) {
  return new RoadWebSecurityConfigurerAdapter() {
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.authenticationProvider(authenticationProvider);
    }

  };
}
 
Example #7
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 #8
Source File: AuthConfiguration.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Bean
public LdapAuthenticationProvider ldapAuthProvider() {
  BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
  bindAuthenticator.setUserSearch(userSearch());
  DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator(
      ldapContextSource, null);
  defaultAuthAutoConfiguration.setIgnorePartialResultException(true);
  defaultAuthAutoConfiguration.setSearchSubtree(true);
  // Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider,
  // use userId in LDAP system instead of userId input by user.
  return new ApolloLdapAuthenticationProvider(
      bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties);
}
 
Example #9
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
public LdapAuthenticationProvider authenticationProvider(BindAuthenticator ba,
                                                         LdapAuthoritiesPopulator lap,
                                                         UserDetailsContextMapper cm){
    return new LdapAuthenticationProvider(ba, lap){{
        setUserDetailsContextMapper(cm);
    }};
}
 
Example #10
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Bean
public LdapAuthenticationProvider authenticationProvider(BindAuthenticator ba,
                                                         LdapAuthoritiesPopulator lap,
                                                         UserDetailsContextMapper cm){
    return new LdapAuthenticationProvider(ba, lap){{
        setUserDetailsContextMapper(cm);
    }};
}
 
Example #11
Source File: LoginActionsTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticationLDAPUserIT() throws Exception {
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.isAuthenticated()).thenReturn(true);
    LdapAuthenticationProvider ldapAuthenticationProvider = Mockito.mock(LdapAuthenticationProvider.class);
    Mockito.when(ldapAuthenticationProvider.authenticate(Mockito.any(Authentication.class))).thenReturn(authentication);
    LdapManager mockLdapManager = Mockito.mock(LdapManager.class);
    Mockito.when(mockLdapManager.isLdapEnabled()).thenReturn(true);
    Mockito.when(mockLdapManager.getAuthenticationProvider()).thenReturn(Optional.of(ldapAuthenticationProvider));

    LoginActions loginActions = new LoginActions(authenticationProvider);
    boolean authenticated = loginActions.authenticateUser(mockLoginRestModel.createRestModel());
    assertTrue(authenticated);
}
 
Example #12
Source File: LdapManager.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
public Optional<LdapAuthenticationProvider> getAuthenticationProvider() throws AlertConfigurationException {
    try {
        FieldAccessor fieldAccessor = getCurrentConfiguration();
        return createAuthProvider(fieldAccessor);
    } catch (AlertDatabaseConstraintException ex) {
        throw new AlertConfigurationException("Error creating LDAP Context Source", ex);
    }
}
 
Example #13
Source File: TokenAuthenticationService.java    From heimdall with 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 #14
Source File: LdapManager.java    From blackduck-alert with Apache License 2.0 4 votes vote down vote up
private LdapAuthenticationProvider updateAuthenticationProvider(FieldAccessor configurationModel, LdapContextSource contextSource) throws AlertConfigurationException {
    LdapAuthenticator authenticator = createAuthenticator(configurationModel, contextSource);
    LdapAuthoritiesPopulator ldapAuthoritiesPopulator = createAuthoritiesPopulator(configurationModel, contextSource);
    return new LdapAuthenticationProvider(authenticator, ldapAuthoritiesPopulator);
}
 
Example #15
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 4 votes vote down vote up
@Bean
public LdapAuthenticationProvider authenticationProvider(BindAuthenticator ba,
                                                         LdapAuthoritiesPopulator lap){
    return new LdapAuthenticationProvider(ba, lap);
}
 
Example #16
Source File: AtlasLdapAuthenticationProvider.java    From atlas with Apache License 2.0 4 votes vote down vote up
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 #17
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 #18
Source File: LdapAuthenticationProviderConfigurer.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public void configure(B builder) throws Exception {
    LdapAuthenticationProvider provider = postProcess(build());
    builder.authenticationProvider(provider);
}
 
Example #19
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 #20
Source File: AtlasLdapAuthenticationProvider.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
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 #21
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
private Authentication getLdapBindAuthentication(Authentication authentication) {
	try {
		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");
		String rangerLdapBase = PropertiesUtil.getProperty("ranger.ldap.base.dn", "");
		String rangerLdapBindDN = PropertiesUtil.getProperty("ranger.ldap.bind.dn", "");
		String rangerLdapBindPassword = PropertiesUtil.getProperty("ranger.ldap.bind.password", "");
		String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.referral", "follow");
		String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.user.searchfilter", "(uid={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(rangerLdapURL);
		ldapContextSource.setUserDn(rangerLdapBindDN);
		ldapContextSource.setPassword(rangerLdapBindPassword);
		ldapContextSource.setReferral(rangerLdapReferral);
		ldapContextSource.setCacheEnvironmentProperties(false);
		ldapContextSource.setAnonymousReadOnly(false);
		ldapContextSource.setPooled(true);
		if (rangerIsStartTlsEnabled) {
			ldapContextSource.setPooled(false);
			ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy());
		}
		ldapContextSource.afterPropertiesSet();

		DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase);
		defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute);
		defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter);
		defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);

		//String searchFilter="(uid={0})";
		if (rangerLdapUserSearchFilter==null||rangerLdapUserSearchFilter.trim().isEmpty()) {
			rangerLdapUserSearchFilter="(uid={0})";
		}
		FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapBase, rangerLdapUserSearchFilter,ldapContextSource);
		userSearch.setSearchSubtree(true);

		BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
		bindAuthenticator.setUserSearch(userSearch);
		String[] userDnPatterns = new String[] { rangerLdapUserDNPattern };
		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(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
Source File: LdapSecurityConfiguration.java    From data-highway with Apache License 2.0 4 votes vote down vote up
@Bean
public LdapAuthenticationProvider authenticationProvider(
    BindAuthenticator bindAuthenticator,
    LdapAuthoritiesPopulator authoritiesPopulator) {
  return new LdapAuthenticationProvider(bindAuthenticator, authoritiesPopulator);
}
 
Example #23
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;
}