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

The following examples show how to use org.springframework.ldap.core.DirContextOperations. 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
Source Project: Spring-5.0-Projects   Source File: LdapAuthRepositoryCustomImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void createByBindOperation(LdapAuthUser ldapAuthUser) {
	
	DirContextOperations ctx = new DirContextAdapter();
	ctx.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson","inetOrgPerson"});
	ctx.setAttributeValue("cn", ldapAuthUser.getFirstName());
	ctx.setAttributeValue("sn", ldapAuthUser.getSurName());
	ctx.setAttributeValue("uid", ldapAuthUser.getUserName());
	ctx.setAttributeValue("userPassword", ldapAuthUser.getPassword());
	
	Name dn = LdapNameBuilder.newInstance()
		      .add("ou=users")
		      .add("uid=bpatel")
		      .build();
	
	ctx.setDn(dn);
	ldapTemplate.bind(ctx);
	
}
 
Example 2
Source Project: heimdall   Source File: HeimdallLdapAuthoritiesPopulator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If it can not find the user it creates one from the {@link DirContextOperations} provided.<br>
 * <br>
 * {@inheritDoc}
 */
@Transactional
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {

     User user = repository.findByUserNameAndType(username, TypeUser.LDAP);

     if (user == null) {
          User addUser = new User();
          addUser.setEmail(userData.getStringAttribute("mail"));
          addUser.setFirstName(userData.getStringAttribute("givenName"));
          addUser.setLastName(userData.getStringAttribute("sn"));
          addUser.setType(TypeUser.LDAP);
          addUser.setPassword(UUID.randomUUID().toString());
          addUser.setUserName(username);
          
          Set<Role> roles = roleRepository.findByName(Role.DEFAULT);
          addUser.setRoles(roles);
          
          repository.save(addUser);
          user = addUser;
     }

     return getAuthorities(user.getRoles());
}
 
Example 3
@Test(expected = RuntimeException.class)
public void testMapUserFromContext_empty_mail() throws Exception {
    DirContextOperations ctx = createMock(DirContextOperations.class);

    final String username = "johnldap";

    expect(userService.getUserByUsername(username)).andReturn(null).once();
    expect(ctx.attributeExists(MAIL_ATTRIBUTE_NAME)).andReturn(true);
    expect(ctx.getStringAttribute(MAIL_ATTRIBUTE_NAME)).andReturn("").times(1);

    replay(userService, ctx);

    contextMapper.mapUserFromContext(ctx, username, Collections.<GrantedAuthority>emptyList());

    verify(userService, ctx);
    assertFalse("Exception thrown", true);
}
 
Example 4
Source Project: nifi-registry   Source File: LdapUserGroupProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String getUserIdentity(final DirContextOperations ctx) {
    final String identity;

    if (useDnForUserIdentity) {
        identity = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(userIdentityAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("User identity attribute [" + userIdentityAttribute + "] does not exist.");
        }

        try {
            identity = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving user name attribute [" + userIdentityAttribute + "].");
        }
    }

    return IdentityMappingUtil.mapIdentity(identity, identityMappings);
}
 
Example 5
Source Project: nifi-registry   Source File: LdapUserGroupProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String getGroupName(final DirContextOperations ctx) {
    final String name;

    if (useDnForGroupName) {
        name = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(groupNameAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Group identity attribute [" + groupNameAttribute + "] does not exist.");
        }

        try {
            name = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
        }
    }

    return IdentityMappingUtil.mapIdentity(name, groupMappings);
}
 
Example 6
Source Project: nifi   Source File: LdapUserGroupProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String getReferencedGroupValue(final DirContextOperations ctx) {
    final String referencedGroupValue;

    if (StringUtils.isBlank(userGroupReferencedGroupAttribute)) {
        referencedGroupValue = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(userGroupReferencedGroupAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Referenced group value attribute [" + userGroupReferencedGroupAttribute + "] does not exist.");
        }

        try {
            referencedGroupValue = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving referenced group value attribute [" + userGroupReferencedGroupAttribute + "].");
        }
    }

    return groupMembershipEnforceCaseSensitivity ? referencedGroupValue : referencedGroupValue.toLowerCase();
}
 
Example 7
Source Project: cxf   Source File: LdapUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue) {

    ContextMapper<Name> mapper =
        new AbstractContextMapper<Name>() {
            public Name doMapFromContext(DirContextOperations ctx) {
                return ctx.getDn();
            }
        };

    AndFilter filter = new AndFilter();
    filter.and(
        new EqualsFilter("objectclass", objectClass)).and(
            new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<Name> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && !result.isEmpty()) {
        //not only the first one....
        return result.get(0);
    }
    return null;
}
 
Example 8
Source Project: mojito   Source File: UserDetailsContextMapperImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapUserFromContextWhenUserNameIsNotFound() throws Exception {
    when(userRepository.findByUsername(anyString())).thenReturn(null);

    when(userService.createOrUpdateBasicUser(anyObject(), anyString(), anyString(), anyString(),
            anyString())).thenReturn(mock(User.class));

    DirContextOperations dirContextOperations = mock(DirContextOperations.class);
    when(dirContextOperations.getStringAttribute("givenname")).thenReturn("givename");
    when(dirContextOperations.getStringAttribute("sn")).thenReturn("sn");
    when(dirContextOperations.getStringAttribute("cn")).thenReturn("cn");

    UserDetails userDetails = userDetailsContextMapper.mapUserFromContext(dirContextOperations, "testUsername", null);

    Assert.notNull(userDetails);
    verify(dirContextOperations, times(3)).getStringAttribute(anyString());
}
 
Example 9
Source Project: zstack   Source File: LdapUtil.java    License: Apache License 2.0 6 votes vote down vote up
public 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;
    }
}
 
Example 10
Source Project: nifi   Source File: LdapUserGroupProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String getGroupName(final DirContextOperations ctx) {
    final String name;

    if (useDnForGroupName) {
        name = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(groupNameAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Group identity attribute [" + groupNameAttribute + "] does not exist.");
        }

        try {
            name = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
        }
    }

    return IdentityMappingUtil.mapIdentity(name, groupMappings);
}
 
Example 11
@Test
public void testMapUserFromContext_new_no_displayname() throws Exception {
    DirContextOperations ctx = createMock(DirContextOperations.class);

    final String username = "johnldap";
    User user = new UserImpl("123", username);

    expect(userService.getUserByUsername(username)).andReturn(null).once();
    expect(ctx.attributeExists(MAIL_ATTRIBUTE_NAME)).andReturn(true);
    expect(ctx.getStringAttribute(MAIL_ATTRIBUTE_NAME)).andReturn("[email protected]").times(2);
    expect(ctx.attributeExists(DISPLAY_NAME_ATTRIBUTE_NAME)).andReturn(false);
    expect(userService.getUserByUsername(username)).andReturn(user).once();
    expectLastCall();

    replay(userService, ctx);

    final UserDetails userDetails =
            contextMapper.mapUserFromContext(ctx, username, Collections.<GrantedAuthority>emptyList());

    verify(userService, ctx);
    assertEquals(user, userDetails);
}
 
Example 12
EntityEmployment.Builder mapBuilderFromContext(DirContextOperations context) {
    final String departmentCode = context.getStringAttribute(getConstants().getDepartmentLdapProperty());
    
    if (departmentCode == null) {
        return null;
    }

    final EntityEmployment.Builder employee = EntityEmployment.Builder.create();
    employee.setId(context.getStringAttribute(getConstants().getEmployeeIdProperty()));
    employee.setEmployeeStatus(
            CodedAttribute.Builder.create(context.getStringAttribute(getConstants().getEmployeeStatusProperty())));
    //employee.setEmployeeTypeCode(context.getStringAttribute(getConstants().getEmployeeTypeProperty()));
    employee.setEmployeeType(CodedAttribute.Builder.create("P"));
    employee.setBaseSalaryAmount(KualiDecimal.ZERO);
    
    employee.setActive(true);
    return employee;
}
 
Example 13
Source Project: nifi   Source File: LdapUserGroupProvider.java    License: Apache License 2.0 6 votes vote down vote up
private String getReferencedUserValue(final DirContextOperations ctx) {
    final String referencedUserValue;

    if (StringUtils.isBlank(groupMemberReferencedUserAttribute)) {
        referencedUserValue = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(groupMemberReferencedUserAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Referenced user value attribute [" + groupMemberReferencedUserAttribute + "] does not exist.");
        }

        try {
            referencedUserValue = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving reference user value attribute [" + groupMemberReferencedUserAttribute + "].");
        }
    }

    return groupMembershipEnforceCaseSensitivity ? referencedUserValue : referencedUserValue.toLowerCase();
}
 
Example 14
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
    Collection<? extends GrantedAuthority> authorities) {
    List<SimpleGrantedAuthority> mockAuthorities = new ArrayList<>();
    // 新建N个角色
    mockAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
    mockAuthorities.add(new SimpleGrantedAuthority("USER"));
    return super.mapUserFromContext(ctx, username, mockAuthorities);
}
 
Example 15
Source Project: taskana   Source File: LdapClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AccessIdRepresentationModel doMapFromContext(final DirContextOperations context) {
  final AccessIdRepresentationModel accessId = new AccessIdRepresentationModel();
  String dn = getDnWithBaseDn(context.getDn().toString());
  accessId.setAccessId(dn); // fully qualified dn
  accessId.setName(context.getStringAttribute(getGroupNameAttribute()));
  return accessId;
}
 
Example 16
Source Project: taskana   Source File: LdapClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AccessIdRepresentationModel doMapFromContext(final DirContextOperations context) {
  final AccessIdRepresentationModel accessId = new AccessIdRepresentationModel();
  accessId.setAccessId(context.getStringAttribute(getUserIdAttribute()));
  String firstName = context.getStringAttribute(getUserFirstnameAttribute());
  String lastName = context.getStringAttribute(getUserLastnameAttribute());
  accessId.setName(String.format("%s, %s", lastName, firstName));
  return accessId;
}
 
Example 17
Source Project: spring-ldap   Source File: LdapTemplatePooledITest.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 verifyThatInvalidConnectionIsAutomaticallyPurged() throws Exception {
       LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway");
       LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif"));

	DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,ou=Sweden");
       assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2");
       assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
       assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2");

       // Shutdown server and kill all existing connections
       LdapTestUtils.shutdownEmbeddedServer();
       LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway");

       try {
           tested.lookup("cn=Some Person2, ou=company1,ou=Sweden");
           fail("Exception expected");
       } catch (Exception expected) {
           // This should fail because the target connection was closed
           assertThat(true).isTrue();
       }

       LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif"));
       // But this should be OK, because the dirty connection should have been automatically purged.
       tested.lookup("cn=Some Person2, ou=company1,ou=Sweden");
   }
 
Example 18
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {

	LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapConfigurer = auth.ldapAuthentication();

	ldapConfigurer.contextSource()
			.url(ldapSecurityProperties.getUrl().toString())
			.managerDn(ldapSecurityProperties.getManagerDn())
			.managerPassword(ldapSecurityProperties.getManagerPassword());

	if (!StringUtils.isEmpty(ldapSecurityProperties.getUserDnPattern())) {
		ldapConfigurer.userDnPatterns(ldapSecurityProperties.getUserDnPattern());
	}

	if (!StringUtils.isEmpty(ldapSecurityProperties.getUserSearchFilter())) {
		ldapConfigurer
				.userSearchBase(ldapSecurityProperties.getUserSearchBase())
				.userSearchFilter(ldapSecurityProperties.getUserSearchFilter());
	}

	if (!StringUtils.isEmpty(ldapSecurityProperties.getGroupSearchFilter())) {
		ldapConfigurer.groupSearchBase(ldapSecurityProperties.getGroupSearchBase())
				.groupSearchFilter(ldapSecurityProperties.getGroupSearchFilter())
				.groupRoleAttribute(ldapSecurityProperties.getGroupRoleAttribute());
	}
	else {
		ldapConfigurer.ldapAuthoritiesPopulator(new LdapAuthoritiesPopulator() {
			@Override
			public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
				return Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"));
			}
		});
	}

}
 
Example 19
@Test
public void verifyRetrievalOfLotsOfAttributeValues() {
    DistinguishedName testgroupDn = new DistinguishedName(OU_DN).append("cn", "testgroup");

    // The 'member' attribute consists of > 1500 entries and will not be returned without range specifier.
    DirContextOperations ctx = ldapTemplate.lookupContext(testgroupDn);
    assertThat(ctx.getStringAttribute("member")).isNull();

    DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper(new String[]{"member", "cn"});
    assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue();

    String[] attributesArray = attributeMapper.getAttributesForLookup();
    assertThat(attributesArray.length).isEqualTo(2);
    assertThat(attributesArray[0]).isEqualTo("member");
    assertThat(attributesArray[1]).isEqualTo("cn");

    // First iteration - there should now be more members left, but all cn values should have been collected.
    ldapTemplate.lookup(testgroupDn, attributesArray, attributeMapper);

    assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue();
    // Only member attribute should be requested in this query.
    attributesArray = attributeMapper.getAttributesForLookup();
    assertThat(attributesArray.length).isEqualTo(1);
    assertThat(attributesArray[0]).isEqualTo("member;Range=1500-*");

    // Second iteration - all data should now have been collected.
    ldapTemplate.lookup(testgroupDn, attributeMapper.getAttributesForLookup(), attributeMapper);
    assertThat(attributeMapper.hasMore()).as("There should be no more results to get").isFalse();

    List memberValues = attributeMapper.getValues("member");
    assertThat(memberValues).isNotNull();
    assertThat(memberValues).hasSize(1501);

    List cnValues = attributeMapper.getValues("cn");
    assertThat(cnValues).isNotNull();
    assertThat(cnValues).hasSize(1);
}
 
Example 20
Source Project: apollo   Source File: ApolloLdapAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages
      .getMessage("LdapAuthenticationProvider.onlySupports",
          "Only UsernamePasswordAuthenticationToken is supported"));
  UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
  String username = userToken.getName();
  String password = (String) authentication.getCredentials();
  if (this.logger.isDebugEnabled()) {
    this.logger.debug("Processing authentication request for user: " + username);
  }

  if (!StringUtils.hasLength(username)) {
    throw new BadCredentialsException(
        this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
  }
  if (!StringUtils.hasLength(password)) {
    throw new BadCredentialsException(this.messages
        .getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
  }
  Assert.notNull(password, "Null password was supplied in authentication token");
  DirContextOperations userData = this.doAuthentication(userToken);
  String loginId = userData.getStringAttribute(properties.getMapping().getLoginId());
  UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, loginId,
      this.loadUserAuthorities(userData, loginId, (String) authentication.getCredentials()));
  return this.createSuccessfulAuthentication(userToken, user);
}
 
Example 21
@Test
@Category(NoAdTest.class)
public void testAuthenticateWithLdapQueryAndMapper() {
    DirContextOperations ctx = tested.authenticate(query()
            .where("objectclass").is("person")
            .and("uid").is("some.person3"),
            "password",
            new LookupAttemptingCallback());

    assertThat(ctx).isNotNull();
    assertThat(ctx.getStringAttribute("uid")).isEqualTo("some.person3");
}
 
Example 22
@Test
public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() {
    DirContextOperations result =
            tested.searchForContext(query()
            .searchScope(SearchScope.ONELEVEL)
            .base("ou=company1,ou=Sweden")
            .where("objectclass").is("person").and("sn").is("Person2"));

    assertThat(result).isNotNull();
    assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
}
 
Example 23
Source Project: hesperides   Source File: LdapSearchContext.java    License: GNU General Public License v3.0 5 votes vote down vote up
public HashSet<String> retrieveParentGroupDNs(String dn) {
    HashSet<String> parentGroupDNs = new HashSet<>();
    try {
        String cn = DirectoryGroupDN.extractCnFromDn(dn);
        String base = getBaseFrom(cn, dn);
        String searchFilter = ldapConfiguration.getSearchFilterForCN(cn);
        DirContextOperations dirContextOperations = searchCNWithRetry(cn, base, searchFilter);
        parentGroupDNs = extractDirectParentGroupDNs(dirContextOperations.getAttributes(""));
    } catch (IncorrectResultSizeDataAccessException e) {
        // On accepte que la recherche ne retourne aucun résultat
    } catch (NamingException exception) {
        throw LdapUtils.convertLdapException(exception);
    }
    return parentGroupDNs;
}
 
Example 24
Source Project: hesperides   Source File: LdapSearchContext.java    License: GNU General Public License v3.0 5 votes vote down vote up
private DirContextOperations searchCNWithRetry(String cn, String base, String searchFilter) {
    if (dirContext == null) {
        // On lazy-load cet attribut pour éviter de faire systématiquement une connexion TCP au serveur LDAP,
        // même quand cela n'est pas nécessaire, comme par exemple dans le cas de extractGroupAuthoritiesRecursivelyWithCache,
        // lorsque le cache contient toutes les infos.
        dirContext = withRetry("ldapBuildContext", "building LDAP context for user=" + username,
                () -> buildSearchContext(username, password));
    }
    return withRetry("ldapSearchCN", "requesting LDAP for CN=" + cn,
            () -> searchCN(dirContext, cn, base, searchFilter));
}
 
Example 25
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearchForContext_LdapQuery() {
    DirContextOperations result = tested.searchForContext(query()
            .where("objectclass").is("person").and("sn").is("Person2"));

    assertThat(result).isNotNull();
    assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
}
 
Example 26
@QueryHandler
@Override
public DirectoryGroupsView onResolveDirectoryGroupCNsQuery(ResolveDirectoryGroupCNsQuery query) {
    if (ldapAuthenticationProvider == null) {
        return DirectoryGroupsView.allUnresolved(query.getDirectoryGroupCNs());
    }
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
    LdapSearchContext ldapSearchContext = createLdapSearchContext(ldapAuthenticationProvider, auth);
    try {
        List<String> unresolvedDirectoryGroupCNs = new ArrayList<>();
        List<String> ambiguousDirectoryGroupCNs = new ArrayList<>();
        List<String> directoryGroupDNs = new ArrayList<>();

        query.getDirectoryGroupCNs().stream().forEach(groupCN -> {
            // On doit bénéficier du cache durant cet appel :
            try {
                DirContextOperations dirContextOperations = ldapSearchContext.searchUserCNWithRetry(groupCN);
                directoryGroupDNs.add(dirContextOperations.getNameInNamespace());
            } catch (IncorrectResultSizeDataAccessException incorrectResultSizeException) {
                if (incorrectResultSizeException.getActualSize() == 0) {
                    unresolvedDirectoryGroupCNs.add(groupCN);
                } else if (incorrectResultSizeException.getActualSize() > 1) {
                    ambiguousDirectoryGroupCNs.add(groupCN);
                }
            }
        });
        return new DirectoryGroupsView(unresolvedDirectoryGroupCNs, ambiguousDirectoryGroupCNs, directoryGroupDNs);
    } finally {
        ldapSearchContext.closeContext();
    }
}
 
Example 27
@Override
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();
    // L'objet retourné est directement passé à loadUserAuthorities par la classe parente :
    return self.searchCN(username, password);
}
 
Example 28
@Override
@Cacheable(cacheNames = USERS_AUTHENTICATION_CACHE_NAME)
// Note: en cas d'exception levée dans cette méthode, rien ne sera mis en cache
public DirContextOperations searchCN(String username, String password) {
    LdapSearchContext ldapSearchContext = createLdapSearchContext(username, password);
    try {
        return ldapSearchContext.searchUserCNWithRetry(username);
    } finally {
        ldapSearchContext.closeContext();
    }
}
 
Example 29
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
	List<GrantedAuthority> mappedAuthorities = new ArrayList<>();
	try {
		for (GrantedAuthority granted : authorities) {
			String mappedAuthority = environment.getProperty("authentication.group.role.mapper."+granted.getAuthority());
			if (mappedAuthority != null && !mappedAuthority.isEmpty()) {
				mappedAuthorities.add(new SimpleGrantedAuthority(mappedAuthority));
			}
		}
	} catch (Exception e){
		LOGGER.error("Failed to load mapped authorities", e);
	}

	io.gravitee.rest.api.idp.api.authentication.UserDetails userDetails =
			new io.gravitee.rest.api.idp.api.authentication.UserDetails(
					ctx.getStringAttribute(identifierAttribute), "", mappedAuthorities);

	String userPhotoAttribute = environment.getProperty("authentication.user.photo-attribute");
       if(userPhotoAttribute == null) {
           userPhotoAttribute = "jpegPhoto";
       }

	userDetails.setFirstname(ctx.getStringAttribute(LDAP_ATTRIBUTE_FIRSTNAME));
	userDetails.setLastname(ctx.getStringAttribute(LDAP_ATTRIBUTE_LASTNAME));
	userDetails.setEmail(ctx.getStringAttribute(LDAP_ATTRIBUTE_MAIL));
	userDetails.setSource(LdapIdentityProvider.PROVIDER_TYPE);
	userDetails.setSourceId(ctx.getNameInNamespace());
	userDetails.setPicture((byte [])ctx.getObjectAttribute(userPhotoAttribute));

	return userDetails;
}
 
Example 30
Source Project: spring-ldap   Source File: LdapTemplateLookup20ITest.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.
 */
public void testThatPlainLookupWorksWithSpring20() {
	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");
}