Search in sources :

Example 6 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project service-authorization by reportportal.

the class LdapUserReplicator method replicateUser.

/**
 * Replicates LDAP user to internal database (if does NOT exist). Creates personal project for that user
 *
 * @param name       Username
 * @param ctx        LDAP context
 * @param attributes Synchronization Attributes
 * @return Internal User representation
 */
public User replicateUser(String name, DirContextOperations ctx, SynchronizationAttributes attributes) {
    String email = (String) ctx.getObjectAttribute(attributes.getEmail());
    if (isNullOrEmpty(email)) {
        throw new UserSynchronizationException("Email not provided");
    }
    email = normalizeId(email);
    String login = normalizeId(name);
    User user = userRepository.findOne(login);
    if (null == user) {
        User newUser = new User();
        newUser.setLogin(login);
        ofNullable(attributes.getFullName()).flatMap(it -> ofNullable(ctx.getStringAttribute(it))).ifPresent(newUser::setFullName);
        ofNullable(attributes.getPhoto()).flatMap(it -> ofNullable(ctx.getObjectAttribute(it))).filter(photo -> photo instanceof byte[]).map(photo -> (byte[]) photo).ifPresent(photo -> newUser.setPhotoId(uploadPhoto(login, photo)));
        checkEmail(email);
        newUser.setEmail(email);
        newUser.setMetaInfo(defaultMetaInfo());
        newUser.setType(UserType.LDAP);
        newUser.setRole(UserRole.USER);
        newUser.setIsExpired(false);
        newUser.setDefaultProject(generatePersonalProject(newUser));
        userRepository.save(newUser);
        user = newUser;
    } else if (!UserType.LDAP.equals(user.getType())) {
        // if user with such login exists, but it's not GitHub user than throw an exception
        throw new UserSynchronizationException("User with login '" + user.getId() + "' already exists");
    }
    return user;
}
Also used : AbstractUserReplicator(com.epam.reportportal.auth.integration.AbstractUserReplicator) DirContextOperations(org.springframework.ldap.core.DirContextOperations) DataStorage(com.epam.ta.reportportal.database.DataStorage) Optional.ofNullable(java.util.Optional.ofNullable) PersonalProjectService(com.epam.ta.reportportal.database.personal.PersonalProjectService) ProjectRepository(com.epam.ta.reportportal.database.dao.ProjectRepository) UserRepository(com.epam.ta.reportportal.database.dao.UserRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) UserRole(com.epam.ta.reportportal.database.entity.user.UserRole) Component(org.springframework.stereotype.Component) EntityUtils.normalizeId(com.epam.ta.reportportal.commons.EntityUtils.normalizeId) SynchronizationAttributes(com.epam.reportportal.auth.store.entity.ldap.SynchronizationAttributes) User(com.epam.ta.reportportal.database.entity.user.User) UserSynchronizationException(com.epam.reportportal.auth.oauth.UserSynchronizationException) UserType(com.epam.ta.reportportal.database.entity.user.UserType) User(com.epam.ta.reportportal.database.entity.user.User) UserSynchronizationException(com.epam.reportportal.auth.oauth.UserSynchronizationException)

Example 7 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project ranger by apache.

the class PasswordComparisonAuthenticator method authenticate.

// ~ Methods
// ========================================================================================================
public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password
    DirContextOperations user = null;
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    Iterator dns = getUserDns(username).iterator();
    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }
    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }
    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'");
    }
    String encodedPassword = passwordEncoder.encode(password);
    byte[] passwordBytes = encodedPassword.getBytes();
    if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
        throw new BadCredentialsException(messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
    }
    return user;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) NameNotFoundException(org.springframework.ldap.NameNotFoundException) Iterator(java.util.Iterator) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 8 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project tutorials by eugenp.

the class LdapClient method modify.

public void modify(final String username, final String password) {
    Name dn = LdapNameBuilder.newInstance().add("ou", "users").add("cn", username).build();
    DirContextOperations context = ldapTemplate.lookupContext(dn);
    context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
    context.setAttributeValue("cn", username);
    context.setAttributeValue("sn", username);
    context.setAttributeValue("userPassword", digestSHA(password));
    ldapTemplate.modifyAttributes(context);
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations) Name(javax.naming.Name)

Example 9 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project opencast by opencast.

the class OpencastLdapAuthoritiesPopulatorTest method doTest.

/**
 * Perform the test of an instance of the class OpencastLdapAuthoritiesPopulator.
 *
 * @param populator
 *          an instance of {@link OpencastLdapAuthoritiesPopulator} to test
 * @param mappings
 *          a {@link Map} containing the LDAP attribute name - value pairs, where the name is a {@link String} and the
 *          value an array of {@code String}s, possibly {@code null} or empty.
 */
private void doTest(OpencastLdapAuthoritiesPopulator populator, Map<String, String[]> mappings, String rolePrefix, String[] excludePrefixes, boolean toUppercase, String[] additionalAuthorities, JpaGroupRoleProvider groupRoleProvider) {
    DirContextOperations dirContextMock = EasyMock.createNiceMock(DirContextOperations.class);
    // Populate the DirContextOperations class
    for (String attrName : mappings.keySet()) {
        EasyMock.expect(dirContextMock.getStringAttributes(attrName)).andReturn(mappings.get(attrName)).anyTimes();
    }
    EasyMock.replay(dirContextMock);
    // Prepare the expected result
    HashSet<GrantedAuthority> expectedResult = new HashSet<>();
    for (String attrName : mappings.keySet()) {
        if (mappings.get(attrName) != null) {
            for (String attrValues : mappings.get(attrName)) {
                addRoles(expectedResult, rolePrefix, excludePrefixes, toUppercase, groupRoleProvider, org, attrValues.split(","));
            }
        }
    }
    // Add the internal roles
    for (Role role : DEFAULT_INTERNAL_ROLES) {
        expectedResult.add(new SimpleGrantedAuthority(role.getName()));
    }
    // Add the additional authorities
    addRoles(expectedResult, rolePrefix, excludePrefixes, toUppercase, groupRoleProvider, org, additionalAuthorities);
    // Check the response is correct
    checkResponse(populator.getGrantedAuthorities(dirContextMock, USERNAME), expectedResult);
}
Also used : Role(org.opencastproject.security.api.Role) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DirContextOperations(org.springframework.ldap.core.DirContextOperations) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HashSet(java.util.HashSet)

Example 10 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project nifi-registry by apache.

the class LdapUserGroupProvider method load.

/**
 * Reloads the tenants.
 */
private void load(final ContextSource contextSource) {
    // create the ldapTemplate based on the context source. use a single source context to use the same connection
    // to support paging when configured
    final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
    try {
        final List<User> userList = new ArrayList<>();
        final List<Group> groupList = new ArrayList<>();
        // group dn -> user identifiers lookup
        final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();
        // user dn -> user lookup
        final Map<String, User> userLookup = new HashMap<>();
        if (performUserSearch) {
            // search controls
            final SearchControls userControls = new SearchControls();
            userControls.setSearchScope(userSearchScope.ordinal());
            // consider paging support for users
            final DirContextProcessor userProcessor;
            if (pageSize == null) {
                userProcessor = new NullDirContextProcessor();
            } else {
                userProcessor = new PagedResultsDirContextProcessor(pageSize);
            }
            // looking for objects matching the user object class
            final AndFilter userFilter = new AndFilter();
            userFilter.and(new EqualsFilter("objectClass", userObjectClass));
            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(userSearchFilter)) {
                userFilter.and(new HardcodedFilter(userSearchFilter));
            }
            do {
                userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() {

                    @Override
                    protected User doMapFromContext(DirContextOperations ctx) {
                        // get the user identity
                        final String identity = getUserIdentity(ctx);
                        // build the user
                        final User user = new User.Builder().identifierGenerateFromSeed(identity).identity(identity).build();
                        // store the user for group member later
                        userLookup.put(getReferencedUserValue(ctx), user);
                        if (StringUtils.isNotBlank(userGroupNameAttribute)) {
                            final Attribute attributeGroups = ctx.getAttributes().get(userGroupNameAttribute);
                            if (attributeGroups == null) {
                                logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership.");
                            } else {
                                try {
                                    final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups.getAll();
                                    while (groupValues.hasMoreElements()) {
                                        // store the group -> user identifier mapping
                                        groupToUserIdentifierMappings.computeIfAbsent(groupValues.next(), g -> new HashSet<>()).add(user.getIdentifier());
                                    }
                                } catch (NamingException e) {
                                    throw new AuthorizationAccessException("Error while retrieving user group name attribute [" + userIdentityAttribute + "].");
                                }
                            }
                        }
                        return user;
                    }
                }, userProcessor));
            } while (hasMorePages(userProcessor));
        }
        if (performGroupSearch) {
            final SearchControls groupControls = new SearchControls();
            groupControls.setSearchScope(groupSearchScope.ordinal());
            // consider paging support for groups
            final DirContextProcessor groupProcessor;
            if (pageSize == null) {
                groupProcessor = new NullDirContextProcessor();
            } else {
                groupProcessor = new PagedResultsDirContextProcessor(pageSize);
            }
            // looking for objects matching the group object class
            AndFilter groupFilter = new AndFilter();
            groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));
            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(groupSearchFilter)) {
                groupFilter.and(new HardcodedFilter(groupSearchFilter));
            }
            do {
                groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() {

                    @Override
                    protected Group doMapFromContext(DirContextOperations ctx) {
                        final String dn = ctx.getDn().toString();
                        // get the group identity
                        final String name = getGroupName(ctx);
                        // get the value of this group that may associate it to users
                        final String referencedGroupValue = getReferencedGroupValue(ctx);
                        if (!StringUtils.isBlank(groupMemberAttribute)) {
                            Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
                            if (attributeUsers == null) {
                                logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership.");
                            } else {
                                try {
                                    final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers.getAll();
                                    while (userValues.hasMoreElements()) {
                                        final String userValue = userValues.next();
                                        if (performUserSearch) {
                                            // find the user by it's referenced attribute and add the identifier to this group
                                            final User user = userLookup.get(userValue);
                                            // ensure the user is known
                                            if (user != null) {
                                                groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
                                            } else {
                                                logger.warn(String.format("%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue));
                                            }
                                        } else {
                                            // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
                                            final String userDn = userValue;
                                            final String userIdentity;
                                            if (useDnForUserIdentity) {
                                                // use the user value to avoid the unnecessary look up
                                                userIdentity = userDn;
                                            } else {
                                                // lookup the user to extract the user identity
                                                userIdentity = getUserIdentity((DirContextAdapter) ldapTemplate.lookup(userDn));
                                            }
                                            // build the user
                                            final User user = new User.Builder().identifierGenerateFromSeed(userIdentity).identity(userIdentity).build();
                                            // add this user
                                            userList.add(user);
                                            groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
                                        }
                                    }
                                } catch (NamingException e) {
                                    throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
                                }
                            }
                        }
                        // build this group
                        final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(name).name(name);
                        // add all users that were associated with this referenced group attribute
                        if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
                            groupToUserIdentifierMappings.remove(referencedGroupValue).forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                        }
                        return groupBuilder.build();
                    }
                }, groupProcessor));
            } while (hasMorePages(groupProcessor));
            // any remaining groupDn's were referenced by a user but not found while searching groups
            groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
                logger.warn(String.format("[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
            });
        } else {
            // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn
            // groups are not being searched so lookup any groups identified while searching users
            groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
                final String groupName;
                if (useDnForGroupName) {
                    // use the dn to avoid the unnecessary look up
                    groupName = groupDn;
                } else {
                    groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
                }
                // define the group
                final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName).name(groupName);
                // add each user
                userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                // build the group
                groupList.add(groupBuilder.build());
            });
        }
        // record the updated tenants
        tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
    } finally {
        singleContextSource.destroy();
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) AbstractContextMapper(org.springframework.ldap.core.support.AbstractContextMapper) AndFilter(org.springframework.ldap.filter.AndFilter) ClientAuth(org.apache.nifi.registry.security.util.SslContextFactory.ClientAuth) LoggerFactory(org.slf4j.LoggerFactory) LdapTemplate(org.springframework.ldap.core.LdapTemplate) NamingException(javax.naming.NamingException) KeyStoreException(java.security.KeyStoreException) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(javax.naming.directory.Attribute) Map(java.util.Map) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) ThreadFactory(java.util.concurrent.ThreadFactory) LdapsSocketFactory(org.apache.nifi.registry.security.ldap.LdapsSocketFactory) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) AuthorizerContext(org.apache.nifi.registry.security.authorization.annotation.AuthorizerContext) UserGroupProvider(org.apache.nifi.registry.security.authorization.UserGroupProvider) Set(java.util.Set) KeyManagementException(java.security.KeyManagementException) HardcodedFilter(org.springframework.ldap.filter.HardcodedFilter) LdapAuthenticationStrategy(org.apache.nifi.registry.security.ldap.LdapAuthenticationStrategy) SslContextFactory(org.apache.nifi.registry.security.util.SslContextFactory) Executors(java.util.concurrent.Executors) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NamingEnumeration(javax.naming.NamingEnumeration) SingleContextSource(org.springframework.ldap.core.support.SingleContextSource) IdentityMapping(org.apache.nifi.registry.properties.util.IdentityMapping) DirContextOperations(org.springframework.ldap.core.DirContextOperations) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) ReferralStrategy(org.apache.nifi.registry.security.ldap.ReferralStrategy) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) DirContextProcessor(org.springframework.ldap.core.DirContextProcessor) IdentityMappingUtil(org.apache.nifi.registry.properties.util.IdentityMappingUtil) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) SearchControls(javax.naming.directory.SearchControls) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Group(org.apache.nifi.registry.security.authorization.Group) SimpleDirContextAuthenticationStrategy(org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy) UserGroupProviderInitializationContext(org.apache.nifi.registry.security.authorization.UserGroupProviderInitializationContext) NiFiRegistryProperties(org.apache.nifi.registry.properties.NiFiRegistryProperties) UserAndGroups(org.apache.nifi.registry.security.authorization.UserAndGroups) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AbstractTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.AbstractTlsDirContextAuthenticationStrategy) SecurityProviderDestructionException(org.apache.nifi.registry.security.exception.SecurityProviderDestructionException) DefaultTlsDirContextAuthenticationStrategy(org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy) Context(javax.naming.Context) AuthorizationAccessException(org.apache.nifi.registry.security.authorization.exception.AuthorizationAccessException) Logger(org.slf4j.Logger) ContextSource(org.springframework.ldap.core.ContextSource) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) User(org.apache.nifi.registry.security.authorization.User) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) AuthorizerConfigurationContext(org.apache.nifi.registry.security.authorization.AuthorizerConfigurationContext) PropertyValue(org.apache.nifi.registry.util.PropertyValue) Collections(java.util.Collections) FormatUtils(org.apache.nifi.registry.util.FormatUtils) Group(org.apache.nifi.registry.security.authorization.Group) User(org.apache.nifi.registry.security.authorization.User) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) DirContextProcessor(org.springframework.ldap.core.DirContextProcessor) PagedResultsDirContextProcessor(org.springframework.ldap.control.PagedResultsDirContextProcessor) LdapTemplate(org.springframework.ldap.core.LdapTemplate) AuthorizationAccessException(org.apache.nifi.registry.security.authorization.exception.AuthorizationAccessException) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) HashSet(java.util.HashSet) SingleContextSource(org.springframework.ldap.core.support.SingleContextSource) NullDirContextProcessor(org.springframework.ldap.core.LdapTemplate.NullDirContextProcessor) HardcodedFilter(org.springframework.ldap.filter.HardcodedFilter) AndFilter(org.springframework.ldap.filter.AndFilter) AbstractContextMapper(org.springframework.ldap.core.support.AbstractContextMapper) DirContextOperations(org.springframework.ldap.core.DirContextOperations)

Aggregations

DirContextOperations (org.springframework.ldap.core.DirContextOperations)89 Name (javax.naming.Name)20 Test (org.junit.jupiter.api.Test)13 Test (org.junit.Test)9 UserDetails (org.springframework.security.core.userdetails.UserDetails)9 HashSet (java.util.HashSet)8 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)8 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)7 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)7 FilterBasedLdapUserSearch (org.springframework.security.ldap.search.FilterBasedLdapUserSearch)7 LdapConfig (com.thoughtworks.go.config.LdapConfig)6 BaseConfig (com.thoughtworks.go.config.server.security.ldap.BaseConfig)6 BasesConfig (com.thoughtworks.go.config.server.security.ldap.BasesConfig)6 ArrayList (java.util.ArrayList)6 Set (java.util.Set)6 NameNotFoundException (org.springframework.ldap.NameNotFoundException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 PerunAttribute (cz.metacentrum.perun.ldapc.model.PerunAttribute)4 List (java.util.List)4