Search in sources :

Example 1 with AttributesMapper

use of org.springframework.ldap.core.AttributesMapper in project camel by apache.

the class SpringLdapComponentTest method testSearch.

@Test
public void testSearch() throws Exception {
    String dnToSearch = "some dn to bind";
    initializeTest(dnToSearch);
    String filter = "some ldap filter";
    body.put(SpringLdapProducer.FILTER, filter);
    ArgumentCaptor<String> dnCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> filterCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Integer> scopeCaptor = ArgumentCaptor.forClass(Integer.class);
    ArgumentCaptor<AttributesMapper> mapperCaptor = ArgumentCaptor.forClass(AttributesMapper.class);
    List<String> searchResult = Collections.singletonList("some search result");
    when(ldapTemplate.search(any(String.class), any(String.class), any(Integer.class), any(AttributesMapper.class))).thenReturn(searchResult);
    MockEndpoint resultEndpoint = (MockEndpoint) context.getEndpoint("mock:result");
    resultEndpoint.expectedBodiesReceived(Collections.singletonList(searchResult));
    producer.sendBody("direct:start", body);
    Mockito.verify(ldapTemplate).search(dnCaptor.capture(), filterCaptor.capture(), scopeCaptor.capture(), mapperCaptor.capture());
    assertEquals(dnToSearch, dnCaptor.getValue());
    assertEquals((Integer) SearchControls.ONELEVEL_SCOPE, scopeCaptor.getValue());
    assertEquals(filter, filterCaptor.getValue());
    resultEndpoint.assertIsSatisfied();
}
Also used : AttributesMapper(org.springframework.ldap.core.AttributesMapper) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Test(org.junit.Test)

Example 2 with AttributesMapper

use of org.springframework.ldap.core.AttributesMapper in project cxf by apache.

the class LdapClaimsHandler method retrieveClaimValues.

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    final String user;
    boolean useLdapLookup = false;
    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
        return new ProcessedClaimCollection();
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("User must not be null");
            return new ProcessedClaimCollection();
        }
        useLdapLookup = LdapUtils.isDN(user);
    } else {
        LOG.warning("Principal is null");
        return new ProcessedClaimCollection();
    }
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Retrieve claims for user " + user);
    }
    Map<String, Attribute> ldapAttributes = null;
    if (useLdapLookup) {
        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;
            }
        };
        ldapAttributes = ldap.lookup(user, mapper);
    } else {
        List<String> searchAttributeList = new ArrayList<>();
        for (Claim claim : claims) {
            String claimType = claim.getClaimType().toString();
            if (getClaimsLdapAttributeMapping().keySet().contains(claimType)) {
                searchAttributeList.add(getClaimsLdapAttributeMapping().get(claimType));
            } else {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("Unsupported claim: " + claimType);
                }
            }
        }
        String[] searchAttributes = searchAttributeList.toArray(new String[0]);
        if (this.userBaseDn != null) {
            ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(), this.getUserNameAttribute(), user, searchAttributes);
        }
        if (this.userBaseDNs != null && (ldapAttributes == null || ldapAttributes.isEmpty())) {
            for (String userBase : userBaseDNs) {
                ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, userBase, this.getObjectClass(), this.getUserNameAttribute(), user, searchAttributes);
                if (ldapAttributes != null && !ldapAttributes.isEmpty()) {
                    // User found
                    break;
                }
            }
        }
    }
    if (ldapAttributes == null || ldapAttributes.isEmpty()) {
        // No result
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("User '" + user + "' not found");
        }
        return new ProcessedClaimCollection();
    }
    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
    for (Claim claim : claims) {
        ProcessedClaim c = processClaim(claim, ldapAttributes, principal);
        if (c != null) {
            // c.setIssuer(issuer);
            // c.setOriginalIssuer(originalIssuer);
            // c.setNamespace(namespace);
            claimsColl.add(c);
        }
    }
    return claimsColl;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Attribute(javax.naming.directory.Attribute) AttributesMapper(org.springframework.ldap.core.AttributesMapper) HashMap(java.util.HashMap) Attributes(javax.naming.directory.Attributes) ArrayList(java.util.ArrayList) StringTokenizer(java.util.StringTokenizer) X500Principal(javax.security.auth.x500.X500Principal) HashMap(java.util.HashMap) Map(java.util.Map) X500Principal(javax.security.auth.x500.X500Principal) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) Claim(org.apache.cxf.rt.security.claims.Claim)

Example 3 with AttributesMapper

use of org.springframework.ldap.core.AttributesMapper in project cxf by apache.

the class UserServiceImpl method getAttributesOfEntry.

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;
}
Also used : Attribute(javax.naming.directory.Attribute) AttributesMapper(org.springframework.ldap.core.AttributesMapper) HashMap(java.util.HashMap) Attributes(javax.naming.directory.Attributes) HardcodedFilter(org.springframework.ldap.filter.HardcodedFilter) AndFilter(org.springframework.ldap.filter.AndFilter) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with AttributesMapper

use of org.springframework.ldap.core.AttributesMapper in project metron by apache.

the class KnoxSSOAuthenticationFilter method getAuthentication.

/**
 * Builds the Spring Authentication object using the supplied user name and groups looked up from LDAP.  Groups are currently
 * mapped directly to Spring roles by converting to upper case and prepending the name with "ROLE_".
 * @param userName The username to build the Authentication object with.
 * @param httpRequest HttpServletRequest
 * @return Authentication object for the given user.
 */
protected Authentication getAuthentication(String userName, HttpServletRequest httpRequest) {
    String ldapName = LdapNameBuilder.newInstance().add(userSearchBase).add("uid", userName).build().toString();
    // Search ldap for a user's groups and convert to a Spring role
    List<GrantedAuthority> grantedAuths = ldapTemplate.search(query().where("objectclass").is("groupOfNames").and("member").is(ldapName), (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get()).stream().map(group -> String.format("%s%s", SECURITY_ROLE_PREFIX, group.toUpperCase())).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    final UserDetails principal = new User(userName, "", grantedAuths);
    final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
    authentication.setDetails(webDetails);
    return authentication;
}
Also used : WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) FilterChain(javax.servlet.FilterChain) ServletException(javax.servlet.ServletException) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(org.springframework.security.core.userdetails.User) JWSObject(com.nimbusds.jose.JWSObject) LdapTemplate(org.springframework.ldap.core.LdapTemplate) HttpServletRequest(javax.servlet.http.HttpServletRequest) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) UserDetails(org.springframework.security.core.userdetails.UserDetails) SECURITY_ROLE_PREFIX(org.apache.metron.rest.MetronRestConstants.SECURITY_ROLE_PREFIX) Filter(javax.servlet.Filter) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Cookie(javax.servlet.http.Cookie) ParseException(java.text.ParseException) Path(java.nio.file.Path) JWSVerifier(com.nimbusds.jose.JWSVerifier) ServletRequest(javax.servlet.ServletRequest) Logger(org.slf4j.Logger) Files(java.nio.file.Files) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) LdapNameBuilder(org.springframework.ldap.support.LdapNameBuilder) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) AttributesMapper(org.springframework.ldap.core.AttributesMapper) SecurityContext(org.springframework.security.core.context.SecurityContext) ServletResponse(javax.servlet.ServletResponse) LdapQueryBuilder.query(org.springframework.ldap.query.LdapQueryBuilder.query) FilterConfig(javax.servlet.FilterConfig) SecurityUtils(org.apache.metron.rest.security.SecurityUtils) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Authentication(org.springframework.security.core.Authentication) UserDetails(org.springframework.security.core.userdetails.UserDetails) User(org.springframework.security.core.userdetails.User) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 5 with AttributesMapper

use of org.springframework.ldap.core.AttributesMapper in project cxf by apache.

the class LdapUtils method getAttributeOfEntries.

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 };
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass));
    if (filters != null) {
        for (Filter f : filters) {
            filter.and(f);
        }
    }
    List<?> 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;
}
Also used : AttributesMapper(org.springframework.ldap.core.AttributesMapper) Attributes(javax.naming.directory.Attributes) AndFilter(org.springframework.ldap.filter.AndFilter) AndFilter(org.springframework.ldap.filter.AndFilter) Filter(org.springframework.ldap.filter.Filter) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) List(java.util.List) EqualsFilter(org.springframework.ldap.filter.EqualsFilter)

Aggregations

AttributesMapper (org.springframework.ldap.core.AttributesMapper)6 Attributes (javax.naming.directory.Attributes)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Attribute (javax.naming.directory.Attribute)3 AndFilter (org.springframework.ldap.filter.AndFilter)3 EqualsFilter (org.springframework.ldap.filter.EqualsFilter)3 List (java.util.List)2 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 JWSObject (com.nimbusds.jose.JWSObject)1 JWSVerifier (com.nimbusds.jose.JWSVerifier)1 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 IOException (java.io.IOException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Principal (java.security.Principal)1 CertificateException (java.security.cert.CertificateException)1 ParseException (java.text.ParseException)1