org.springframework.ldap.core.LdapTemplate Java Examples

The following examples show how to use org.springframework.ldap.core.LdapTemplate. 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: LdapUpgradeExtension.java    From zstack with 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 #3
Source File: GatekeeperCommonConfig.java    From Gatekeeper with 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 #4
Source File: OdmManagerImpl.java    From spring-ldap with 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 #5
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: TestContextSourceFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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 #8
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 #9
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 #10
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 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 #11
Source File: SpringLdap.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #12
Source File: SingleContextSource.java    From spring-ldap with 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 #13
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with 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 #14
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with 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 #15
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with 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 #16
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with 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 #17
Source File: LdapTemplateParser.java    From spring-ldap with 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 #18
Source File: LdapServiceImplTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws UnknownHostException {
    testUser = buildTestUser();
    slcUser = buildSlcUser();
    uid = testUser.getUid();
    group = buildTestGroup();

    ldapTemplate = Mockito.mock(LdapTemplate.class);

    DistinguishedName dn = new DistinguishedName("ou=LocalNew");
    String[] attributes = new String[] {"*", LdapService.CREATE_TIMESTAMP, LdapService.MODIFY_TIMESTAMP };

    // mock: ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] {"*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper())
    Mockito.when(ldapTemplate.search(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=person)(uid=slcoperator))"),
            Mockito.eq(SearchControls.SUBTREE_SCOPE),
            Mockito.eq(attributes),
            Mockito.any(UserContextMapper.class))).thenReturn(Arrays.asList(slcUser));

    // mock: ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper());
    Mockito.when(ldapTemplate.searchForObject(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=posixGroup)(cn=SLC Operator))"),
            Mockito.any(GroupContextMapper.class)))
        .thenReturn(group);

    // mock: ldapTemplate.search(dn, filter.toString(), new GroupContextMapper()
    Mockito.when(ldapTemplate.search(
            Mockito.eq(dn),
            Mockito.eq("(&(objectclass=posixGroup)(memberuid=slcoperator))"),
            Mockito.any(GroupContextMapper.class)))
        .thenReturn(Arrays.asList(group));

    ldapService.setLdapTemplate(ldapTemplate);
}
 
Example #19
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeOfEntries(
    LdapTemplate ldapTemplate, String baseDN,
    String objectClass, List<Filter> filters,
    String searchAttribute) {

    List<String> ldapAttributes = null;

    AttributesMapper<Object> mapper =
        new AttributesMapper<Object>() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                return attrEnum.next().get();
            }
            return null;
        }
    };

    String[] searchAttributes = new String[] {searchAttribute};

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass));
    if (filters != null) {
        for (Filter f : filters) {
            filter.and(f);
        }
    }

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((List<?>)result);
    }

    return ldapAttributes;
}
 
Example #20
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeOfEntries(
    LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String searchAttribute) {

    List<Filter> filters =
        Collections.singletonList(new EqualsFilter(filterAttributeName, filterAttributeValue));
    return getAttributeOfEntries(ldapTemplate, baseDN, objectClass, filters, searchAttribute);
}
 
Example #21
Source File: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example #23
Source File: LdapTemplateLookup25ITest.java    From spring-ldap with 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 #24
Source File: LdapTemplateLookup25ITest.java    From spring-ldap with 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);
}
 
Example #25
Source File: UserServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
                                                           String objectClass, String searchFilter,
                                                           String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
        public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
            Map<String, Attribute> map = new HashMap<>();
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                Attribute att = attrEnum.next();
                map.put(att.getID(), att);
            }
            return map;
        }
    };

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass)).and(new HardcodedFilter(searchFilter));

    List<?> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example #26
Source File: KnoxSSOAuthenticationFilterTest.java    From metron with 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 #27
Source File: KnoxSSOAuthenticationFilter.java    From metron with 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 File: LdapUtil.java    From zstack with 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 #29
Source File: LdapUtil.java    From zstack with 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 #30
Source File: LdapTemplateNamespaceHandlerTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyParseWithDefaultValues() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-defaults.xml");
    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);

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

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

    assertThat(LdapUtils.emptyLdapName()).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.FALSE).isEqualTo(getInternalState(contextSource, "pooled"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly"));
    assertThat(getInternalState(contextSource, "referral")).isNull();

    assertThat(outerContextSource).isSameAs(getInternalState(ldapTemplate, "contextSource"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(ldapTemplate, "ignorePartialResultException"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(ldapTemplate, "ignoreNameNotFoundException"));
    assertThat(0).isEqualTo(getInternalState(ldapTemplate, "defaultCountLimit"));
    assertThat(0).isEqualTo(getInternalState(ldapTemplate, "defaultTimeLimit"));
    assertThat(SearchControls.SUBTREE_SCOPE).isEqualTo(getInternalState(ldapTemplate, "defaultSearchScope"));
}