org.springframework.ldap.core.DirContextOperations Java Examples
The following examples show how to use
org.springframework.ldap.core.DirContextOperations.
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: LdapUserGroupProvider.java From nifi with Apache License 2.0 | 6 votes |
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 #2
Source File: LdapUtils.java From cxf with Apache License 2.0 | 6 votes |
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 #3
Source File: LdapAuthRepositoryCustomImpl.java From Spring-5.0-Projects with MIT License | 6 votes |
@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 #4
Source File: LdapUserDetailsContextMapperTest.java From attic-rave with Apache License 2.0 | 6 votes |
@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 #5
Source File: EntityEmploymentMapper.java From rice with Educational Community License v2.0 | 6 votes |
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 #6
Source File: HeimdallLdapAuthoritiesPopulator.java From heimdall with Apache License 2.0 | 6 votes |
/** * 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 #7
Source File: LdapUserDetailsContextMapperTest.java From attic-rave with Apache License 2.0 | 6 votes |
@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 #8
Source File: LdapUserGroupProvider.java From nifi with Apache License 2.0 | 6 votes |
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 #9
Source File: LdapUserGroupProvider.java From nifi with Apache License 2.0 | 6 votes |
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 #10
Source File: LdapUserGroupProvider.java From nifi-registry with Apache License 2.0 | 6 votes |
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
Source File: LdapUtil.java From zstack with Apache License 2.0 | 6 votes |
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 #12
Source File: LdapUserGroupProvider.java From nifi-registry with Apache License 2.0 | 6 votes |
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 #13
Source File: UserDetailsContextMapperImplTest.java From mojito with Apache License 2.0 | 6 votes |
@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 #14
Source File: EntityPrivacyPreferencesMapper.java From rice with Educational Community License v2.0 | 5 votes |
EntityPrivacyPreferences.Builder mapBuilderFromContext(DirContextOperations context) { final String entityId = context.getStringAttribute(getConstants().getKimLdapIdProperty()); final EntityPrivacyPreferences.Builder person = EntityPrivacyPreferences.Builder.create(entityId); person.setSuppressName(false); person.setSuppressEmail(false); person.setSuppressPhone(false); person.setSuppressAddress(false); person.setSuppressPersonal(true); return person; }
Example #15
Source File: LdapTemplateSearchResultITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test(expected = EmptyResultDataAccessException.class) public void testSearchForObjectNoHits() { tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", new AbstractContextMapper() { @Override protected Object doMapFromContext(DirContextOperations ctx) { return ctx; } }); }
Example #16
Source File: ActiveDirectoryLdapAuthoritiesPopulator.java From maven-framework-project with MIT License | 5 votes |
@Override public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) { String[] groups = userData.getStringAttributes("memberOf"); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for (String group : groups) { LdapRdn authority = new DistinguishedName(group).removeLast(); authorities.add(new SimpleGrantedAuthority(authority.getValue())); } return authorities; }
Example #17
Source File: LdapTemplateModifyITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testModifyAttributes_AddAttributeValueWithExistingValue() { DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); ctx.addAttributeValue("uniqueMember", "cn=Some Person,ou=company1,ou=Norway," + base); tested.modifyAttributes(ctx); assertThat(true).isTrue(); }
Example #18
Source File: DefaultController.java From spring-ldap with Apache License 2.0 | 5 votes |
@Override protected String getLinkForNode(DirContextOperations node) { String[] objectClassValues = node.getStringAttributes("objectClass"); if (containsValue(objectClassValues, "person")) { Name dn = node.getDn(); String country = encodeValue(LdapUtils.getStringValue(dn, "c")); String company = encodeValue(LdapUtils.getStringValue(dn, "ou")); String fullName = encodeValue(LdapUtils.getStringValue(dn, "cn")); return "showPerson.do?country=" + country + "&company=" + company + "&fullName=" + fullName; } else { return super.getLinkForNode(node); } }
Example #19
Source File: OsiamLdapAuthenticationProvider.java From osiam with MIT License | 5 votes |
private User synchronizeLdapData(DirContextOperations ldapUserData, User user) { if (user == null) { return userProvisioning.create(osiamLdapUserContextMapper.mapUser(ldapUserData)); } else if (syncUserData) { return userProvisioning.update( user.getId(), osiamLdapUserContextMapper.mapUpdateUser(user, ldapUserData) .getScimConformUpdateUser()); } return user; }
Example #20
Source File: LdapUpgradeExtension.java From zstack with Apache License 2.0 | 5 votes |
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 #21
Source File: EntityEmailMapper.java From rice with Educational Community License v2.0 | 5 votes |
EntityEmail.Builder mapBuilderFromContext(DirContextOperations context, boolean isdefault) { final EntityEmail.Builder retval = EntityEmail.Builder.create(); final String emailAddress = context.getStringAttribute(getConstants().getEmployeeMailLdapProperty()); retval.setEmailAddress(emailAddress); retval.setEmailType(CodedAttribute.Builder.create("WORK")); retval.setDefaultValue(isdefault); retval.setActive(true); return retval; }
Example #22
Source File: LdapTemplateLookup30ITest.java From spring-ldap with Apache License 2.0 | 5 votes |
/** * This method depends on a DirObjectFactory ( * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) * being set in the ContextSource. */ @Test public void testThatPlainLookupWorksWithSpring30() { 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"); }
Example #23
Source File: LDAPAuthenticator.java From para with Apache License 2.0 | 5 votes |
@Override public DirContextOperations authenticate(Authentication authentication) { try { if (authenticator != null) { return authenticator.authenticate(authentication); } } catch (Exception e) { logger.warn("Failed to authenticate user with LDAP server: {}", e.getMessage()); } throw new AuthenticationServiceException("LDAP user not found."); }
Example #24
Source File: LdapUtil.java From zstack with Apache License 2.0 | 5 votes |
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 #25
Source File: OsiamLdapUserContextMapper.java From osiam with MIT License | 5 votes |
private void updateAddress(UpdateUser.Builder updateBuilder, List<Address> addresses, DirContextOperations ldapUserData) { for (Address address : addresses) { if (address.getType() != null && address.getType().toString().equals(LdapAuthentication.LDAP_PROVIDER)) { updateBuilder.deleteAddress(address); } } List<Address> newAddresses = getAddresses(ldapUserData); if (!newAddresses.isEmpty()) { updateBuilder.addAddress(newAddresses.get(0)); } }
Example #26
Source File: LdapTemplateAuthenticationITest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test(expected = AuthenticationException.class) @Category(NoAdTest.class) public void testAuthenticateWithLdapQueryAndMapperAndInvalidPassword() { DirContextOperations ctx = tested.authenticate(query() .where("objectclass").is("person") .and("uid").is("some.person3"), "invalidpassword", new LookupAttemptingCallback()); }
Example #27
Source File: LdapTemplateLookup20ITest.java From spring-ldap with Apache License 2.0 | 5 votes |
/** * 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"); }
Example #28
Source File: UserDetailsContextPropertiesMapper.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@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 #29
Source File: LdapAuthenticationProvider.java From hesperides with GNU General Public License v3.0 | 5 votes |
@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 #30
Source File: LdapAuthenticationProvider.java From hesperides with GNU General Public License v3.0 | 5 votes |
@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); }