Search in sources :

Example 6 with LdapEntry

use of org.ldaptive.LdapEntry in project cas by apereo.

the class LdapPasswordManagementService method getSecurityQuestions.

@Override
public Map<String, String> getSecurityQuestions(final String username) {
    final Map<String, String> set = new LinkedHashMap<>();
    try {
        final PasswordManagementProperties.Ldap ldap = passwordManagementProperties.getLdap();
        final SearchFilter filter = Beans.newLdaptiveSearchFilter(ldap.getUserFilter(), Beans.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, Arrays.asList(username));
        LOGGER.debug("Constructed LDAP filter [{}] to locate security questions", filter);
        final ConnectionFactory factory = Beans.newLdaptivePooledConnectionFactory(ldap);
        final Response<SearchResult> response = LdapUtils.executeSearchOperation(factory, ldap.getBaseDn(), filter);
        LOGGER.debug("LDAP response for security questions [{}]", response);
        if (LdapUtils.containsResultEntry(response)) {
            final LdapEntry entry = response.getResult().getEntry();
            LOGGER.debug("Located LDAP entry [{}] in the response", entry);
            final Map<String, String> qs = passwordManagementProperties.getLdap().getSecurityQuestionsAttributes();
            LOGGER.debug("Security question attributes are defined to be [{}]", qs);
            qs.forEach((k, v) -> {
                final LdapAttribute q = entry.getAttribute(k);
                final LdapAttribute a = entry.getAttribute(v);
                if (q != null && a != null && StringUtils.isNotBlank(q.getStringValue()) && StringUtils.isNotBlank(a.getStringValue())) {
                    LOGGER.debug("Added security question [{}]", q.getStringValue());
                    set.put(q.getStringValue(), a.getStringValue());
                }
            });
        } else {
            LOGGER.debug("LDAP response did not contain a result for security questions");
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return set;
}
Also used : ConnectionFactory(org.ldaptive.ConnectionFactory) PasswordManagementProperties(org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties) LdapAttribute(org.ldaptive.LdapAttribute) SearchFilter(org.ldaptive.SearchFilter) SearchResult(org.ldaptive.SearchResult) LdapEntry(org.ldaptive.LdapEntry) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with LdapEntry

use of org.ldaptive.LdapEntry in project cas by apereo.

the class LdapPasswordManagementService method findEmail.

@Override
public String findEmail(final String username) {
    try {
        final PasswordManagementProperties.Ldap ldap = passwordManagementProperties.getLdap();
        final SearchFilter filter = Beans.newLdaptiveSearchFilter(ldap.getUserFilter(), Beans.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, Arrays.asList(username));
        LOGGER.debug("Constructed LDAP filter [{}] to locate account email", filter);
        final ConnectionFactory factory = Beans.newLdaptivePooledConnectionFactory(ldap);
        final Response<SearchResult> response = LdapUtils.executeSearchOperation(factory, ldap.getBaseDn(), filter);
        LOGGER.debug("LDAP response to locate account email is [{}]", response);
        if (LdapUtils.containsResultEntry(response)) {
            final LdapEntry entry = response.getResult().getEntry();
            LOGGER.debug("Found LDAP entry [{}] to use for the account email", entry);
            final String attributeName = passwordManagementProperties.getReset().getEmailAttribute();
            final LdapAttribute attr = entry.getAttribute(attributeName);
            if (attr != null) {
                final String email = attr.getStringValue();
                LOGGER.debug("Found email address [{}] for user [{}]. Validating...", email, username);
                if (EmailValidator.getInstance().isValid(email)) {
                    LOGGER.debug("Email address [{}] matches a valid email address", email);
                    return email;
                } else {
                    LOGGER.error("Email [{}] is not a valid address", email);
                }
            } else {
                LOGGER.error("Could not locate an LDAP attribute [{}] for [{}] and base DN [{}]", attributeName, filter.format(), ldap.getBaseDn());
            }
            return null;
        } else {
            LOGGER.error("Could not locate an LDAP entry for [{}] and base DN [{}]", filter.format(), ldap.getBaseDn());
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : ConnectionFactory(org.ldaptive.ConnectionFactory) PasswordManagementProperties(org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties) LdapAttribute(org.ldaptive.LdapAttribute) SearchFilter(org.ldaptive.SearchFilter) SearchResult(org.ldaptive.SearchResult) LdapEntry(org.ldaptive.LdapEntry)

Example 8 with LdapEntry

use of org.ldaptive.LdapEntry in project cas by apereo.

the class LdapSpnegoKnownClientSystemsFilterAction method processSpnegoAttribute.

/**
     * Verify spnego attribute value.
     *
     * @param searchResult the search result
     * @return true if attribute value exists and has a value
     */
protected boolean processSpnegoAttribute(final Response<SearchResult> searchResult) {
    final SearchResult result = searchResult.getResult();
    if (result == null || result.getEntries().isEmpty()) {
        LOGGER.debug("Spnego attribute is not found in the search results");
        return false;
    }
    final LdapEntry entry = result.getEntry();
    final LdapAttribute attribute = entry.getAttribute(this.spnegoAttributeName);
    LOGGER.debug("Spnego attribute [{}] found as [{}] for [{}]", attribute.getName(), attribute.getStringValue(), entry.getDn());
    return verifySpnegoAttributeValue(attribute);
}
Also used : LdapAttribute(org.ldaptive.LdapAttribute) SearchResult(org.ldaptive.SearchResult) LdapEntry(org.ldaptive.LdapEntry)

Example 9 with LdapEntry

use of org.ldaptive.LdapEntry in project cas by apereo.

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        final String username = authentication.getPrincipal().toString();
        final Object credentials = authentication.getCredentials();
        final String password = credentials == null ? null : credentials.toString();
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        final AuthenticationRequest request = new AuthenticationRequest(username, new org.ldaptive.Credential(password), ReturnAttributes.ALL.value());
        final Authenticator authenticator = Beans.newLdaptiveAuthenticator(adminPagesSecurityProperties.getLdap());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        final AuthenticationResponse response = authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.getResult()) {
            final LdapEntry entry = response.getLdapEntry();
            final CommonProfile profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            this.authorizationGenerator.generate(WebUtils.getPac4jJ2EContext(), profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            final Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.addAll(profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            final RequireAnyRoleAuthorizer authorizer = new RequireAnyRoleAuthorizer(adminPagesSecurityProperties.getAdminRoles());
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            final J2EContext context = WebUtils.getPac4jJ2EContext();
            if (authorizer.isAllAuthorized(context, Arrays.asList(profile))) {
                return new UsernamePasswordAuthenticationToken(username, password, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) LdapEntry(org.ldaptive.LdapEntry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) J2EContext(org.pac4j.core.context.J2EContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) CommonProfile(org.pac4j.core.profile.CommonProfile) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) Authenticator(org.ldaptive.auth.Authenticator) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)

Example 10 with LdapEntry

use of org.ldaptive.LdapEntry in project cas by apereo.

the class DefaultLdapRegisteredServiceMapper method mapFromRegisteredService.

@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {
    try {
        if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
            ((AbstractRegisteredService) svc).setId(System.nanoTime());
        }
        final String newDn = getDnForRegisteredService(dn, svc);
        LOGGER.debug("Creating entry [{}]", newDn);
        final Collection<LdapAttribute> attrs = new ArrayList<>();
        attrs.add(new LdapAttribute(ldap.getIdAttribute(), String.valueOf(svc.getId())));
        final StringWriter writer = new StringWriter();
        this.jsonSerializer.to(writer, svc);
        attrs.add(new LdapAttribute(ldap.getServiceDefinitionAttribute(), writer.toString()));
        attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, "top", ldap.getObjectClass()));
        return new LdapEntry(newDn, attrs);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) LdapAttribute(org.ldaptive.LdapAttribute) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) LdapEntry(org.ldaptive.LdapEntry)

Aggregations

LdapEntry (org.ldaptive.LdapEntry)13 LdapAttribute (org.ldaptive.LdapAttribute)9 SearchResult (org.ldaptive.SearchResult)8 LdapException (org.ldaptive.LdapException)6 ArrayList (java.util.ArrayList)3 PasswordManagementProperties (org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties)2 ConnectionFactory (org.ldaptive.ConnectionFactory)2 SearchFilter (org.ldaptive.SearchFilter)2 AddRequest (com.unboundid.ldap.sdk.AddRequest)1 Attribute (com.unboundid.ldap.sdk.Attribute)1 IOException (java.io.IOException)1 StringWriter (java.io.StringWriter)1 CertificateException (java.security.cert.CertificateException)1 LinkedHashMap (java.util.LinkedHashMap)1 GraphicalUserAuthenticationProperties (org.apereo.cas.configuration.model.support.gua.GraphicalUserAuthenticationProperties)1 AbstractRegisteredService (org.apereo.cas.services.AbstractRegisteredService)1 AuthenticationRequest (org.ldaptive.auth.AuthenticationRequest)1 AuthenticationResponse (org.ldaptive.auth.AuthenticationResponse)1 Authenticator (org.ldaptive.auth.Authenticator)1 RequireAnyRoleAuthorizer (org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)1