Search in sources :

Example 41 with Attributes

use of javax.naming.directory.Attributes in project cxf by apache.

the class LdapCertificateRepo method getCertificatesFromLdap.

private List<X509Certificate> getCertificatesFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509Certificate> certificates = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream((byte[]) attribute.get()));
                certificates.add(certificate);
            }
        }
        return certificates;
    } catch (CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) CertificateException(java.security.cert.CertificateException) NamingException(javax.naming.NamingException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 42 with Attributes

use of javax.naming.directory.Attributes in project cxf by apache.

the class LdapCertificateRepo method getCRLsFromLdap.

private List<X509CRL> getCRLsFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509CRL> crls = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream((byte[]) attribute.get()));
                crls.add(crl);
            }
        }
        return crls;
    } catch (CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (CRLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : X509CRL(java.security.cert.X509CRL) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) NamingException(javax.naming.NamingException) CRLException(java.security.cert.CRLException)

Example 43 with Attributes

use of javax.naming.directory.Attributes in project uPortal by Jasig.

the class SimpleLdapSecurityContext method authenticate.

/**
 * Authenticates the user.
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;
    ldapConn = LdapServices.getDefaultLdapServer();
    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;
        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());
        try {
            conn = ldapConn.getConnection();
            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore()) {
                            log.error("SimpleLdapSecurityContext: user not found: {}", this.myPrincipal.UID);
                        }
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in {} for {}", dnBuffer.toString(), attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);
                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User {} ({}) is authenticated", this.myPrincipal.UID, this.myPrincipal.FullName);
                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        }
                    // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: {}", this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavailable");
            }
        } catch (final NamingException ne) {
            log.error("Error getting connection to LDAP server.", ne);
        }
    } else {
        // If the principal and/or credential are missing, the context authentication
        // simply fails. It should not be construed that this is an error. It happens for guest
        // access.
        log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}
Also used : ILdapServer(org.apereo.portal.ldap.ILdapServer) AuthenticationException(javax.naming.AuthenticationException) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Example 44 with Attributes

use of javax.naming.directory.Attributes in project Payara by payara.

the class ProxyDirContext method cacheLoad.

/**
 * Load entry into cache.
 */
protected void cacheLoad(CacheEntry entry) {
    String name = entry.name;
    // Retrieve missing info
    boolean exists = true;
    // Retrieving attributes
    if (entry.attributes == null) {
        try {
            Attributes attributes = dirContext.getAttributes(entry.name);
            if (!(attributes instanceof ResourceAttributes)) {
                entry.attributes = new ResourceAttributes(attributes);
            } else {
                entry.attributes = (ResourceAttributes) attributes;
            }
        } catch (NamingException e) {
            exists = false;
        }
    }
    // Retriving object
    if ((exists) && (entry.resource == null) && (entry.context == null)) {
        try {
            Object object = dirContext.lookup(name);
            if (object instanceof InputStream) {
                entry.resource = new Resource((InputStream) object);
            } else if (object instanceof DirContext) {
                entry.context = (DirContext) object;
            } else if (object instanceof Resource) {
                entry.resource = (Resource) object;
            } else {
                entry.resource = new Resource(new ByteArrayInputStream(object.toString().getBytes(Charset.defaultCharset())));
            }
        } catch (NamingException e) {
            exists = false;
        }
    }
    // Load object content
    if ((exists) && (entry.resource != null) && (entry.resource.getContent() == null) && (entry.attributes.getContentLength() >= 0) && (entry.attributes.getContentLength() < (cacheObjectMaxSize * 1024L))) {
        int length = (int) entry.attributes.getContentLength();
        // The entry size is 1 + the resource size in KB, if it will be
        // cached
        entry.size += (entry.attributes.getContentLength() / 1024);
        InputStream is = null;
        try {
            is = entry.resource.streamContent();
            int pos = 0;
            byte[] b = new byte[length];
            while (pos < length) {
                int n = is.read(b, pos, length - pos);
                if (n < 0)
                    break;
                pos = pos + n;
            }
            entry.resource.setContent(b);
        } catch (IOException e) {
        // Ignore
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            // Ignore
            }
        }
    }
    // Set existence flag
    entry.exists = exists;
    // Set timestamp
    entry.timestamp = System.currentTimeMillis() + cacheTTL;
    // Add new entry to cache
    synchronized (cache) {
        // Check cache size, and remove elements if too big
        if ((cache.lookup(name) == null) && cache.allocate(entry.size)) {
            cache.load(entry);
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) NamingException(javax.naming.NamingException)

Example 45 with Attributes

use of javax.naming.directory.Attributes in project Payara by payara.

the class ProxyDirContext method getAttributes.

/**
 * Retrieves all of the attributes associated with a named object.
 *
 * @return the set of attributes associated with name
 * @param name the name of the object from which to retrieve attributes
 * @exception NamingException if a naming exception is encountered
 */
public Attributes getAttributes(String name) throws NamingException {
    CacheEntry entry = cacheLookup(name);
    if (entry != null) {
        if (!entry.exists) {
            throw notFoundException;
        }
        return entry.attributes;
    }
    Attributes attributes = dirContext.getAttributes(parseName(name));
    if (!(attributes instanceof ResourceAttributes)) {
        attributes = new ResourceAttributes(attributes);
    }
    return attributes;
}
Also used : Attributes(javax.naming.directory.Attributes)

Aggregations

Attributes (javax.naming.directory.Attributes)99 Attribute (javax.naming.directory.Attribute)66 NamingException (javax.naming.NamingException)37 BasicAttributes (javax.naming.directory.BasicAttributes)36 SearchResult (javax.naming.directory.SearchResult)36 BasicAttribute (javax.naming.directory.BasicAttribute)29 SearchControls (javax.naming.directory.SearchControls)24 ArrayList (java.util.ArrayList)22 DirContext (javax.naming.directory.DirContext)22 NamingEnumeration (javax.naming.NamingEnumeration)20 IOException (java.io.IOException)13 InitialDirContext (javax.naming.directory.InitialDirContext)13 Hashtable (java.util.Hashtable)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 LdapContext (javax.naming.ldap.LdapContext)8 File (java.io.File)7 InputStream (java.io.InputStream)7 MutablePartitionConfiguration (org.apache.directory.server.core.configuration.MutablePartitionConfiguration)7