Java Code Examples for org.springframework.ldap.core.LdapTemplate

The following examples show how to use org.springframework.ldap.core.LdapTemplate. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public GatekeeperOpenLDAPAuthorizationService(LdapTemplate ldapTemplate,
                                                         Supplier<IGatekeeperUserProfile> gatekeeperUserProfileSupplier,
                                                         GatekeeperAuthProperties gatekeeperAuthProperties) {
    super(gatekeeperUserProfileSupplier);
    this.ldapProperties = gatekeeperAuthProperties.getLdap();
    this.ldapTemplate = ldapTemplate;
    this.ldapUserCn = ldapProperties.getUsersCnAttribute();
    this.ldapUserId = ldapProperties.getUsersIdAttribute();
    this.ldapUserDn = ldapProperties.getUsersDnAttribute();
    this.ldapObjectClass = ldapProperties.getObjectClass();
    this.ldapUserEmail = ldapProperties.getUsersEmailAttribute();
    this.ldapUserName = ldapProperties.getUsersNameAttribute();
    this.ldapUserGroupsBase = ldapProperties.getAwsGroupsBase() != null ? ldapProperties.getAwsGroupsBase() : ldapProperties.getGroupsBase();

    logger.info("Initialized GatekeeperOpenLDAPAuthorizationService with cn=" + this.ldapUserCn + " id=" + ldapUserId
    + " dn=" + ldapUserDn + " email=" + ldapUserEmail + " name=" + ldapUserName);
}
 
Example 2
Source Project: Gatekeeper   Source File: GatekeeperCommonConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public GatekeeperAuthorizationService gatekeeperLDAPAuthorizationService(LdapTemplate ldapTemplate,
                                                                         Supplier<IGatekeeperUserProfile> gatekeeperUserProfileSupplier){
    //Sets to AD if true
    if(gatekeeperAuthProperties.getLdap().getIsActiveDirectory()) {
        logger.info("Setting Authorization to work with Active Directory");
        return new GatekeeperActiveDirectoryLDAPAuthorizationService(ldapTemplate,
                gatekeeperUserProfileSupplier,
                gatekeeperAuthProperties);
    }

    logger.info("Setting Authorization to work with OpenLDAP");
    //Defaults to OpenLDAP otherwise
    return new GatekeeperOpenLDAPAuthorizationService(ldapTemplate,
                gatekeeperUserProfileSupplier,
                gatekeeperAuthProperties);
}
 
Example 3
public void queryVulnerableToInjection(LdapTemplate template, String jndiInjectMe, SearchControls searchControls, DirContextProcessor dirContextProcessor) throws NamingException {
    template.list(jndiInjectMe);
    template.list(jndiInjectMe, new DefaultNameClassPairMapper());
    template.list(jndiInjectMe, new CountNameClassPairCallbackHandler());

    template.lookup(jndiInjectMe);
    template.lookup(jndiInjectMe, new DefaultIncrementalAttributesMapper());
    template.lookup(jndiInjectMe, new LdapEntryIdentificationContextMapper());

    template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",searchControls,new DefaultIncrementalAttributesMapper(), dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper(),dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler(),dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,true,new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",searchControls, new DefaultIncrementalAttributesMapper());
}
 
Example 4
Source Project: cuba   Source File: LdapLoginProvider.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void init() {
    if (webLdapConfig.getLdapEnabled()) {
        ldapContextSource = new LdapContextSource();

        checkRequiredConfigProperties(webLdapConfig);

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

        ldapContextSource.afterPropertiesSet();

        ldapTemplate = new LdapTemplate(ldapContextSource);
        ldapTemplate.setIgnorePartialResultException(true);
    }
}
 
Example 5
Source Project: zstack   Source File: LdapUpgradeExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void updateLdapUidToLdapDn() {
    if(!isLdapServerExist()){
        return;
    }

    if(!isBindingExist()){
        return;
    }

    try {
        LdapTemplateContextSource ldapTemplateContextSource = readLdapServerConfiguration();
        LdapTemplate ldapTemplate = ldapTemplateContextSource.getLdapTemplate();

        List<LdapAccountRefVO> refs = Q.New(LdapAccountRefVO.class).list();
        for(LdapAccountRefVO ref : refs){
            update(ldapTemplate, ref);
        }

    }catch (Throwable t){
        logger.error("update ldapUid to ldapDn An error occurred", t);
    }
}
 
Example 6
Source Project: spring-ldap   Source File: LdapTemplateParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(LdapTemplate.class);

    String contextSourceRef = getString(element, ATT_CONTEXT_SOURCE_REF, ContextSourceParser.DEFAULT_ID);
    builder.addPropertyReference("contextSource", contextSourceRef);
    builder.addPropertyValue("defaultCountLimit", getInt(element, ATT_COUNT_LIMIT, DEFAULT_COUNT_LIMIT));
    builder.addPropertyValue("defaultTimeLimit", getInt(element, ATT_TIME_LIMIT, DEFAULT_TIME_LIMIT));

    String searchScope = getString(element, ATT_SEARCH_SCOPE, SearchScope.SUBTREE.toString());
    builder.addPropertyValue("defaultSearchScope", SearchScope.valueOf(searchScope).getId());
    builder.addPropertyValue("ignorePartialResultException", getBoolean(element, ATT_IGNORE_PARTIAL_RESULT, false));
    builder.addPropertyValue("ignoreNameNotFoundException", getBoolean(element, ATT_IGNORE_NAME_NOT_FOUND, false));

    String odmRef = element.getAttribute(ATT_ODM_REF);
    if(StringUtils.hasText(odmRef)) {
        builder.addPropertyReference("objectDirectoryMapper", odmRef);
    }

    String id = getString(element, AbstractBeanDefinitionParser.ID_ATTRIBUTE, DEFAULT_ID);

    BeanDefinition beanDefinition = builder.getBeanDefinition();
    parserContext.registerBeanComponent(new BeanComponentDefinition(beanDefinition, id));

    return beanDefinition;
}
 
Example 7
Source Project: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void doFilterShouldContinueOnBasicAuthenticationHeader() throws Exception {
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          mock(LdapTemplate.class)
  ));
  HttpServletRequest request = mock(HttpServletRequest.class);
  ServletResponse response = mock(ServletResponse.class);
  FilterChain chain = mock(FilterChain.class);

  when(request.getHeader("Authorization")).thenReturn("Basic ");

  knoxSSOAuthenticationFilter.doFilter(request, response, chain);

  verify(knoxSSOAuthenticationFilter, times(0)).getJWTFromCookie(request);
  verify(chain).doFilter(request, response);
  verifyNoMoreInteractions(chain);
}
 
Example 8
Source Project: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void doFilterShouldContinueOnParseException() throws Exception {
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          mock(LdapTemplate.class)
  ));
  HttpServletRequest request = mock(HttpServletRequest.class);
  ServletResponse response = mock(ServletResponse.class);
  FilterChain chain = mock(FilterChain.class);

  when(request.getHeader("Authorization")).thenReturn(null);
  doReturn("serializedJWT").when(knoxSSOAuthenticationFilter).getJWTFromCookie(request);
  doThrow(new ParseException("parse exception", 0)).when(knoxSSOAuthenticationFilter).parseJWT(any());

  knoxSSOAuthenticationFilter.doFilter(request, response, chain);

  verify(knoxSSOAuthenticationFilter, times(0)).getAuthentication("userName", request);
  verify(chain).doFilter(request, response);
  verifyNoMoreInteractions(chain);
}
 
Example 9
Source Project: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void doFilterShouldContinueOnInvalidToken() throws Exception {
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          mock(LdapTemplate.class)
  ));
  HttpServletRequest request = mock(HttpServletRequest.class);
  ServletResponse response = mock(ServletResponse.class);
  FilterChain chain = mock(FilterChain.class);
  SignedJWT signedJWT = mock(SignedJWT.class);
  JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder().subject("userName").build();

  when(request.getHeader("Authorization")).thenReturn(null);
  doReturn("serializedJWT").when(knoxSSOAuthenticationFilter).getJWTFromCookie(request);
  doReturn(signedJWT).when(knoxSSOAuthenticationFilter).parseJWT(any());
  when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet);
  doReturn(false).when(knoxSSOAuthenticationFilter).isValid(signedJWT, "userName");

  knoxSSOAuthenticationFilter.doFilter(request, response, chain);

  verify(knoxSSOAuthenticationFilter, times(0)).getAuthentication("userName", request);
  verify(chain).doFilter(request, response);
  verifyNoMoreInteractions(chain);
}
 
Example 10
Source Project: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAuthenticationShouldProperlyPopulateAuthentication() {
  LdapTemplate ldapTemplate = mock(LdapTemplate.class);
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("ou=people,dc=hadoop,dc=apache,dc=org",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          ldapTemplate
  ));

  HttpServletRequest request = mock(HttpServletRequest.class);

  when(ldapTemplate.search(any(LdapQuery.class), any(AttributesMapper.class))).thenReturn(Arrays.asList("USER", "ADMIN"));

  Authentication authentication = knoxSSOAuthenticationFilter.getAuthentication("userName", request);
  Object[] grantedAuthorities = authentication.getAuthorities().toArray();
  assertEquals("ROLE_USER", grantedAuthorities[0].toString());
  assertEquals("ROLE_ADMIN", grantedAuthorities[1].toString());
  assertEquals("userName", authentication.getName());
}
 
Example 11
Source Project: spring-ldap   Source File: SingleContextSource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct a SingleContextSource and execute the LdapOperationsCallback using the created instance.
 * This makes sure the same connection will be used for all operations inside the LdapOperationsCallback,
 * which is particularly useful when working with e.g. Paged Results as these typically require the exact
 * same connection to be used for all requests involving the same cookie..
 * The SingleContextSource instance will be properly disposed of once the operation has been completed.
 *
 * @param contextSource The target ContextSource to retrieve a DirContext from
 * @param callback the callback to perform the Ldap operations
 * @param useReadOnly if <code>true</code>, use the {@link org.springframework.ldap.core.ContextSource#getReadOnlyContext()}
 *                    method on the target ContextSource to get the actual DirContext instance, if <code>false</code>,
 *                    use {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()}.
 * @param ignorePartialResultException Used for populating this property on the created LdapTemplate instance.
 * @param ignoreNameNotFoundException Used for populating this property on the created LdapTemplate instance.
 * @return the result returned from the callback.
 * @since 2.0
 */
public static <T> T doWithSingleContext(ContextSource contextSource,
                                        LdapOperationsCallback<T> callback,
                                        boolean useReadOnly,
                                        boolean ignorePartialResultException,
                                        boolean ignoreNameNotFoundException) {
    SingleContextSource singleContextSource;
    if (useReadOnly) {
        singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    } else {
        singleContextSource = new SingleContextSource(contextSource.getReadWriteContext());
    }

    LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
    ldapTemplate.setIgnorePartialResultException(ignorePartialResultException);
    ldapTemplate.setIgnoreNameNotFoundException(ignoreNameNotFoundException);

    try {
        return callback.doWithLdapOperations(ldapTemplate);
    } finally {
        singleContextSource.destroy();
    }
}
 
Example 12
Source Project: ob1k   Source File: LdapCredentialsAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This constructor creates a LdapCredentialsAuthenticator that authenticates against an LDAP server
 * that supports anonymous requests
 *
 * @param ldapHost    the LDAP server host
 * @param ldapPort    the LDAP server port
 * @param usersOuPath the path for the organizational unit under which users are found
 */
public LdapCredentialsAuthenticator(final String ldapHost,
                                    final int ldapPort,
                                    final String usersOuPath) {
  Assert.hasText(ldapHost, "Invalid ldapHost");
  Assert.isTrue(ldapPort > 0);
  Assert.hasText(usersOuPath, "Invalid usersOuPath");

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

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

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

  ldapTemplate = new LdapTemplate(contextSource);
  this.id = calculateId(ldapHost, ldapPort, usersOuPath);
}
 
Example 14
@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 15
Source Project: spring-ldap   Source File: OdmManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public OdmManagerImpl(ConverterManager converterManager,
                      LdapOperations ldapOperations,
                      Set<Class<?>> managedClasses) {
    this.ldapTemplate = (LdapTemplate)ldapOperations;
    objectDirectoryMapper = new DefaultObjectDirectoryMapper();

    if(converterManager != null) {
        objectDirectoryMapper.setConverterManager(converterManager);
    }

    if (managedClasses!=null) {
        for (Class<?> managedClass: managedClasses) {
            addManagedClass(managedClass);
        }
    }

    this.ldapTemplate.setObjectDirectoryMapper(objectDirectoryMapper);
}
 
Example 16
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-testContextSource.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example 17
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-ldifPopulator.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example 18
@Test
  public void testServerStartup() throws Exception {
      ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
      LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
      assertNotNull(ldapTemplate);

List<String> list = ldapTemplate.search(
		LdapQueryBuilder.query().where("objectclass").is("person"),
		new AttributesMapper<String>() {
			public String mapFromAttributes(Attributes attrs)
					throws NamingException {
				return (String) attrs.get("cn").get();
			}
		});
      assertEquals(5, list.size());
  }
 
Example 19
@Test
public void verifyParseWithCustomValues() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-values.xml");
    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    DirContextAuthenticationStrategy authenticationStrategy = ctx.getBean(DirContextAuthenticationStrategy.class);

    assertThat(outerContextSource).isNotNull();
    assertThat(ldapTemplate).isNotNull();

    assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
    ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();

    assertThat(LdapUtils.newLdapName("dc=261consulting,dc=com")).isEqualTo(getInternalState(contextSource, "base"));
    assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn"));
    assertThat("apassword").isEqualTo(getInternalState(contextSource, "password"));
    assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(contextSource, "pooled"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly"));
    assertThat("follow").isEqualTo(getInternalState(contextSource, "referral"));
    assertThat(authenticationStrategy).isSameAs(getInternalState(contextSource, "authenticationStrategy"));

    assertThat(outerContextSource).isSameAs(getInternalState(ldapTemplate, "contextSource"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(ldapTemplate, "ignorePartialResultException"));
    assertThat(Boolean.TRUE).isEqualTo(getInternalState(ldapTemplate, "ignoreNameNotFoundException"));
    assertThat(100).isEqualTo(getInternalState(ldapTemplate, "defaultCountLimit"));
    assertThat(200).isEqualTo(getInternalState(ldapTemplate, "defaultTimeLimit"));
    assertThat(SearchControls.OBJECT_SCOPE).isEqualTo(getInternalState(ldapTemplate, "defaultSearchScope"));
}
 
Example 20
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 21
Source Project: Gatekeeper   Source File: GatekeeperLdapLookupService.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public GatekeeperLdapLookupService(LdapTemplate ldapTemplate,
                                   GatekeeperAuthProperties gatekeeperAuthProperties) {
    this.ldapTemplate = ldapTemplate;
    this.ldapProperties = gatekeeperAuthProperties.getLdap();
    this.ldapObjectClass = ldapProperties.getObjectClass();
    this.ldapUserId = ldapProperties.getUsersIdAttribute();
    this.ldapUserDn = ldapProperties.getUsersDnAttribute();
    this.ldapUserEmail = ldapProperties.getUsersEmailAttribute();
    this.ldapUserName = ldapProperties.getUsersNameAttribute();
}
 
Example 22
Source Project: spring-ldap   Source File: LdapTemplateLookup25ITest.java    License: Apache License 2.0 5 votes vote down vote up
private void performTestAndShutdownContext(ClassPathXmlApplicationContext ctx, LdapTemplate tested) {
    try {
        DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,c=Sweden");

        assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2");
        assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
        assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2");
    } finally {
        ctx.close();
    }
}
 
Example 23
Source Project: herd   Source File: LdapOperationsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch()
{
    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(LDAP_URL);
    contextSource.setBase(LDAP_BASE);
    contextSource.setUserDn(LDAP_USER_DN);
    contextSource.setPassword(PASSWORD);
    contextSource.afterPropertiesSet();

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

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

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

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

    // Validate the results.
    assertEquals(
        Collections.singletonList(new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER)),
        result);
}
 
Example 24
Source Project: zstack   Source File: LdapUpgradeExtension.java    License: Apache License 2.0 5 votes vote down vote up
private void update(LdapTemplate ldapTemplate, LdapAccountRefVO ref){
    String uid = ref.getLdapUid();

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("uid", ref.getLdapUid()));

    List<Object> result = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(result.size() == 0){
        logger.error(String.format("Can not find ldapUid[%s] dn", uid));
        return;
    }

    if(result.size() > 1){
        logger.error(String.format("ldapUid[%s] More than one dn result", uid));
        return;
    }

    String dn = result.get(0).toString();
    ref.setLdapUid(dn);
    dbf.update(ref);
    logger.info(String.format("update ldapUid[%s] to ldapDn[%s] success", uid, dn));
}
 
Example 25
Source Project: zstack   Source File: LdapUtil.java    License: Apache License 2.0 5 votes vote down vote up
void findLdapDnMemberOfList(LdapTemplate ldapTemplate, String ldapDn, List<String> resultDnList, List<String> dnIgnoreList){
    if(dnIgnoreList.contains(ldapDn)){
        return;
    }

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(getMemberKey(), ldapDn));

    List<Object> groupList = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(groupList.isEmpty()){
        dnIgnoreList.add(ldapDn);
        return;
    }

    for(Object groupObj : groupList){
        if(groupObj == null || !(groupObj instanceof String)){
            continue;
        }

        String groupDn = (String)groupObj;

        if(resultDnList.contains(groupDn)){
            continue;
        }

        resultDnList.add(groupDn);
        findLdapDnMemberOfList(ldapTemplate, groupDn, resultDnList, dnIgnoreList);
    }
}
 
Example 26
Source Project: zstack   Source File: LdapUtil.java    License: Apache License 2.0 5 votes vote down vote up
private String getFullUserDn(LdapTemplate ldapTemplate, String filter) {
    String dn;
    try {
        List<Object> result = ldapTemplate.search("", filter, new AbstractContextMapper<Object>() {
            @Override
            protected Object doMapFromContext(DirContextOperations ctx) {
                return ctx.getNameInNamespace();
            }
        });
        if (result.size() == 1) {
            dn = result.get(0).toString();
        } else if (result.size() > 1) {
            throw new OperationFailureException(err(
                    LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, "More than one ldap search result"));
        } else {
            return "";
        }
        logger.info(String.format("getDn success filter:%s, dn:%s", filter, dn));
    } catch (NamingException e) {
        LdapServerVO ldapServerVO = getLdapServer();
        throw new OperationFailureException(err(
                LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, "You'd better check the LDAP/AD server[url:%s, baseDN:%s, encryption:%s, username:%s, password:******]" +
                        " configuration and test connection first.getDn error filter:%s",
                ldapServerVO.getUrl(), ldapServerVO.getBase(),
                ldapServerVO.getEncryption(), ldapServerVO.getUsername(), filter));
    }
    return dn;
}
 
Example 27
Source Project: metron   Source File: KnoxSSOAuthenticationFilter.java    License: Apache License 2.0 5 votes vote down vote up
public KnoxSSOAuthenticationFilter(String userSearchBase,
                                   Path knoxKeyFile,
                                   String knoxKeyString,
                                   String knoxCookie,
                                   LdapTemplate ldapTemplate) {
  this.userSearchBase = userSearchBase;
  this.knoxKeyFile = knoxKeyFile;
  this.knoxKeyString = knoxKeyString;
  this.knoxCookie = knoxCookie;
  if (ldapTemplate == null) {
    throw new IllegalStateException("KnoxSSO requires LDAP. You must add 'ldap' to the active profiles.");
  }
  this.ldapTemplate = ldapTemplate;
}
 
Example 28
Source Project: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void doFilterShouldProperlySetAuthentication() throws Exception {
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          mock(LdapTemplate.class)
  ));
  HttpServletRequest request = mock(HttpServletRequest.class);
  ServletResponse response = mock(ServletResponse.class);
  FilterChain chain = mock(FilterChain.class);
  SignedJWT signedJWT = mock(SignedJWT.class);
  JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder().subject("userName").build();
  Authentication authentication = mock(Authentication.class);
  SecurityContext securityContext = mock(SecurityContext.class);

  when(request.getHeader("Authorization")).thenReturn(null);
  doReturn("serializedJWT").when(knoxSSOAuthenticationFilter).getJWTFromCookie(request);
  doReturn(signedJWT).when(knoxSSOAuthenticationFilter).parseJWT(any());
  when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet);
  doReturn(true).when(knoxSSOAuthenticationFilter).isValid(signedJWT, "userName");
  doReturn(authentication).when(knoxSSOAuthenticationFilter).getAuthentication("userName", request);
  doReturn(securityContext).when(knoxSSOAuthenticationFilter).getSecurityContext();

  knoxSSOAuthenticationFilter.doFilter(request, response, chain);

  verify(securityContext).setAuthentication(authentication);
  verify(chain).doFilter(request, response);
  verifyNoMoreInteractions(chain, securityContext);
}
 
Example 29
Source Project: spring-ldap   Source File: LdapTemplateLookup25ITest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method depends on a DirObjectFactory (
 * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory})
 * being set in the ContextSource.
 */
   @Test
public void testThatPlainLookupWorksWithSpring25() {
       ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/conf/ldapTemplateTestContext.xml");
       LdapTemplate tested = (LdapTemplate) ctx.getBean("ldapTemplate");

       performTestAndShutdownContext(ctx, tested);
   }
 
Example 30
Source Project: spring-ldap   Source File: LdapTemplateLookup25ITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testThatNamespaceConfigurationWorksWithSpring25() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/conf/ldapTemplateNamespaceTestContext.xml");
    LdapTemplate tested = (LdapTemplate) ctx.getBean("ldapTemplate");

    performTestAndShutdownContext(ctx, tested);
}