@Bean @ConditionalOnMissingBean public ContextSource ldapContextSource() { LdapContextSource source = new LdapContextSource(); source.setUserDn(this.properties.getUsername()); source.setPassword(this.properties.getPassword()); source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly()); source.setBase(this.properties.getBase()); source.setUrls(this.properties.determineUrls(this.environment)); source.setBaseEnvironmentProperties( Collections.unmodifiableMap(this.properties.getBaseEnvironment())); return source; }
@Override @SuppressWarnings("rawtypes") public void setupEnvironment(Hashtable env, String dn, String password) { super.setupEnvironment(env, dn, password); // Remove the pooling flag unless we are authenticating as the 'manager' // user. if (!DefaultSpringSecurityContextSource.this.userDn.equals(dn) && env.containsKey(SUN_LDAP_POOLING_FLAG)) { DefaultSpringSecurityContextSource.this.logger .debug("Removing pooling flag for user " + dn); env.remove(SUN_LDAP_POOLING_FLAG); } } });
@Bean public RememberMeServices rememberMeServices(String internalSecretKey) { LdapContextSource ldapContext = getLdapContext(); String searchBase = "OU=Users,DC=test,DC=company,DC=com"; String searchFilter = "(&(objectClass=user)(sAMAccountName={0}))"; FilterBasedLdapUserSearch search = new FilterBasedLdapUserSearch(searchBase, searchFilter, ldapContext); search.setSearchSubtree(true); LdapUserDetailsService rememberMeUserDetailsService = new LdapUserDetailsService(search); rememberMeUserDetailsService.setUserDetailsMapper(new CustomUserDetailsServiceImpl()); InMemoryTokenRepositoryImpl rememberMeTokenRepository = new InMemoryTokenRepositoryImpl(); PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices(internalSecretKey, rememberMeUserDetailsService, rememberMeTokenRepository); services.setAlwaysRemember(true); return services; } @Bean public LdapContextSource getLdapContext() { LdapContextSource source = new LdapContextSource(); source.setUserDn("user@"+DOMAIN); source.setPassword("password"); source.setUrl(URL); return source; }
final LdapContextSource context = new LdapContextSource(); context.setAnonymousReadOnly(true); break; default: context.setUserDn(userDn); context.setPassword(password); context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString().equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; context.setReferral(referralStrategy.getValue()); context.setUrls(StringUtils.split(urls));
LdapContextSource buildLdapContextSource(LdapServerInventory inv, Map<String, Object> baseEnvironmentProperties) { LdapContextSource ldapContextSource; ldapContextSource = new LdapContextSource(); ldapContextSource.setUrl(inv.getUrl()); ldapContextSource.setBase(inv.getBase()); ldapContextSource.setUserDn(inv.getUsername()); ldapContextSource.setPassword(inv.getPassword()); ldapContextSource.setDirObjectFactory(DefaultDirObjectFactory.class); if (inv.getEncryption().equals(LdapEncryptionType.TLS.toString())) { setTls(ldapContextSource); } ldapContextSource.setCacheEnvironmentProperties(false); ldapContextSource.setPooled(false); ldapContextSource.setReferral("follow"); if (baseEnvironmentProperties != null && !baseEnvironmentProperties.isEmpty()) { ldapContextSource.setBaseEnvironmentProperties(baseEnvironmentProperties); } try { ldapContextSource.afterPropertiesSet(); logger.info("Test LDAP Context Source loaded "); } catch (Exception e) { logger.error("Test LDAP Context Source not loaded ", e); throw new CloudRuntimeException("Test LDAP Context Source not loaded", e); } return ldapContextSource; }
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); }
public DirContextAuthenticationStrategy getAuthenticationStrategy() throws ClassNotFoundException, NoSuchAlgorithmException, IllegalAccessException, InstantiationException, KeyManagementException { if (!hasText(tlsConfig)) { tlsConfig = NONE; } AbstractTlsDirContextAuthenticationStrategy tlsStrategy; switch (tlsConfig) { case NONE: return new SimpleDirContextAuthenticationStrategy(); case SIMPLE: tlsStrategy = new DefaultTlsDirContextAuthenticationStrategy(); break; case EXTERNAL: tlsStrategy = new ExternalTlsDirContextAuthenticationStrategy(); break; default: throw new IllegalArgumentException(tlsConfig); } tlsStrategy.setHostnameVerifier(new AllowAllHostnameVerifier()); tlsStrategy.setSslSocketFactory(getSSLSocketFactory()); return tlsStrategy; } }
@Override public final String getBaseLdapPathAsString() { return getTargetAsBaseLdapPathSource().getBaseLdapPathAsString(); } }
public FilterBasedLdapUserSearch(String searchBase, String searchFilter, BaseLdapPathContextSource contextSource) { Assert.notNull(contextSource, "contextSource must not be null"); Assert.notNull(searchFilter, "searchFilter must not be null."); Assert.notNull(searchBase, "searchBase must not be null (an empty string is acceptable)."); this.searchFilter = searchFilter; this.contextSource = contextSource; this.searchBase = searchBase; setSearchSubtree(true); if (searchBase.length() == 0) { logger.info("SearchBase not set. Searches will be performed from the root: " + contextSource.getBaseLdapPath()); } }
throw new OperationFailureException(err(LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, "cannot find dn[%s] on ldap server[Address:%s, BaseDN:%s].", fullDn, String.join(", ", ldapTemplateContextSource.getLdapContextSource().getUrls()), ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString()));
@Override protected void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException { super.applyAuthentication(ctx, userDn, password); ctx.reconnect(ctx.getConnectControls()); } }
private String getPartialUserDn(LdapTemplateContextSource ldapTemplateContextSource,String key, String value) { return getFullUserDn(ldapTemplateContextSource.getLdapTemplate(), key, value). replace("," + ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString(), ""); }
@Override protected void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException { super.applyAuthentication(ctx, userDn, password); ctx.reconnect(ctx.getConnectControls()); } }
@Test public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception { final DirContext dirCtx = mock(DirContext.class); final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class); final BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("uid", "bob")); PasswordComparisonAuthenticator authenticator = new PasswordComparisonAuthenticator( source); authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" }); // Get the mock to return an empty attribute set when(source.getReadOnlyContext()).thenReturn(dirCtx); when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))) .thenReturn(attrs); when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org"); // Setup a single return value (i.e. success) final NamingEnumeration searchResults = new BasicAttributes("", null).getAll(); when( dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class), any(SearchControls.class))).thenReturn( searchResults); authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword")); } }
// ... LdapContextSource ctxSrc = new LdapContextSource(); ctxSrc.setUrl("ldap://<ldapUrl>:389"); ctxSrc.setBase("DC=bar,DC=test,DC=foo"); ctxSrc.setUserDn("<username>@bar.test.foo"); ctxSrc.setPassword("<password>"); ctxSrc.afterPropertiesSet(); /* ! */ LdapTemplate tmpl = new LdapTemplate(ctxSrc); // ...
@Override public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException { final LdapContextSource context = new LdapContextSource(); context.setAnonymousReadOnly(true); break; default: context.setUserDn(userDn); context.setPassword(password); context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString().equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; context.setReferral(referralStrategy.getValue()); context.setUrls(StringUtils.split(urls));
DistinguishedName userDn = new DistinguishedName(userDnStr); DistinguishedName fullDn = new DistinguishedName(userDn); fullDn.prepend(ctxSource.getBaseLdapPath()); ctxSource.getBaseLdapPath());
private boolean validateDnExist(LdapTemplateContextSource ldapTemplateContextSource, String fullDn, Filter filter){ try { String dn = fullDn.replace("," + ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString(), ""); List<Object> result = ldapTemplateContextSource.getLdapTemplate().search(dn, filter.toString(), new AbstractContextMapper<Object>() { @Override protected Object doMapFromContext(DirContextOperations ctx) { return ctx.getNameInNamespace(); } }); return result.contains(fullDn); }catch (Exception e){ logger.warn(String.format("validateDnExist[dn=%s, filter=%s] fail", fullDn, filter.toString()), e); return false; } }
@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); }
private boolean validateDnExist(LdapTemplateContextSource ldapTemplateContextSource, String fullDn){ try { String dn = fullDn.replace("," + ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString(), ""); Object result = ldapTemplateContextSource.getLdapTemplate().lookup(dn, new AbstractContextMapper<Object>() { @Override protected Object doMapFromContext(DirContextOperations ctx) { Attributes group = ctx.getAttributes(); return group; } }); return result != null; }catch (Exception e){ logger.warn(String.format("validateDnExist[%s] fail", fullDn), e); return false; } }