Search in sources :

Example 31 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project keywhiz by square.

the class LdapAuthenticator method dnFromUsername.

private String dnFromUsername(String username) throws LDAPException, GeneralSecurityException {
    String baseDN = config.getUserBaseDN();
    String lookup = String.format("(%s=%s)", config.getUserAttribute(), username);
    SearchRequest searchRequest = new SearchRequest(baseDN, SearchScope.SUB, lookup);
    LDAPConnection connection = connectionFactory.getLDAPConnection();
    try {
        SearchResult sr = connection.search(searchRequest);
        if (sr.getEntryCount() == 0) {
            throw new LDAPException(ResultCode.INVALID_CREDENTIALS);
        }
        return sr.getSearchEntries().get(0).getDN();
    } finally {
        connection.close();
    }
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchResult(com.unboundid.ldap.sdk.SearchResult) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection)

Example 32 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project keywhiz by square.

the class LdapAuthenticator method doAuthenticate.

private Optional<User> doAuthenticate(BasicCredentials credentials) {
    User user = null;
    try {
        String username = credentials.getUsername();
        if (!User.isSanitizedUsername(username)) {
            logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN);
            return Optional.empty();
        }
        String userDN = dnFromUsername(username);
        String password = credentials.getPassword();
        // Must have password for current config
        if (Strings.isNullOrEmpty(password)) {
            logger.info("No password for user provided");
            return Optional.empty();
        }
        LDAPConnection authenticatedConnection = connectionFactory.getLDAPConnection(userDN, password);
        authenticatedConnection.close();
        Set<String> requiredRoles = config.getRequiredRoles();
        if (!requiredRoles.isEmpty()) {
            Set<String> roles = rolesFromDN(userDN);
            boolean accessAllowed = false;
            for (String requiredRole : requiredRoles) {
                if (roles.contains(requiredRole)) {
                    accessAllowed = true;
                }
            }
            if (!accessAllowed) {
                logger.warn("User {} not in one of required LDAP roles: [{}].", username, requiredRoles);
                throw new ForbiddenException();
            }
        }
        user = User.named(username);
    } catch (LDAPException le) {
        // The INVALID_CREDENTIALS case is handled by returning an absent optional from this function
        if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
            logger.error("Error connecting to LDAP", le);
            throw Throwables.propagate(le);
        }
    } catch (GeneralSecurityException gse) {
        logger.error("TLS error connecting to LDAP", gse);
        throw Throwables.propagate(gse);
    }
    return Optional.ofNullable(user);
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) User(keywhiz.auth.User) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection)

Example 33 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project CzechIdMng by bcvsolutions.

the class ComplexHrProcessIntegrationTest method startLdapTestServer.

/**
 * Ldap server initialization and start
 */
private void startLdapTestServer() {
    try (InputStream inputStream = new FileInputStream("src/test/resources/eu/bcvsolutions/idm/ldap/schema.ldif")) {
        // Create the configuration to use for the server.
        InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(ldapBaseOU);
        // load schema
        config.addAdditionalBindCredentials(ldapAdminLogin, ldapPassword);
        // InputStream inputStream = new FileInputStream("src/test/resources/eu/bcvsolutions/idm/ldap/schema.ldif");
        final LDIFReader ldifReader = new LDIFReader(inputStream);
        final Entry schemaEntry = ldifReader.readEntry();
        ldifReader.close();
        Schema newSchema = new Schema(schemaEntry);
        config.setSchema(newSchema);
        // Create the directory server instance, populate it with data from the
        // "crossLdapDemoData.ldif" file, and start listening for client connections.
        directoryServer = new InMemoryDirectoryServer(config);
        directoryServer.importFromLDIF(true, "src/test/resources/eu/bcvsolutions/idm/ldap/ldapDemoData.ldif");
        directoryServer.startListening();
        // Get a client connection to the server and use it to perform various
        // operations.
        ldapConnectionInfo = directoryServer.getConnection();
    } catch (LDAPException | IOException | LDIFException e) {
        e.printStackTrace();
        Assert.fail();
    }
    LOG.error(String.format("Ldap server is running and available: %s", ldapConnectionInfo.getHostPort()));
}
Also used : Entry(com.unboundid.ldap.sdk.Entry) LDAPException(com.unboundid.ldap.sdk.LDAPException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) LDIFReader(com.unboundid.ldif.LDIFReader) Schema(com.unboundid.ldap.sdk.schema.Schema) InMemoryDirectoryServerConfig(com.unboundid.ldap.listener.InMemoryDirectoryServerConfig) LDIFException(com.unboundid.ldif.LDIFException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 34 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project oxTrust by GluuFederation.

the class AttributeImportAction method validateFileToImport.

public void validateFileToImport() {
    removeFileDataToImport();
    String dn = attributeService.getDnForAttribute(null);
    if (uploadedFile == null) {
        return;
    }
    ResultCode result = null;
    try (InputStream is = new ByteArrayInputStream(this.fileData)) {
        result = ldifService.validateLdifFile(is, dn);
    } catch (LDAPException ex) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to parse LDIF file");
    } catch (IOException e) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to parse LDIF file");
    }
    if ((result != null) && result.equals(ResultCode.SUCCESS)) {
        this.fileDataToImport.setReady(true);
        this.fileDataToImport.setData(this.fileData);
    } else {
        removeFileDataToImport();
        this.fileDataToImport.setReady(false);
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Invalid LDIF File. Validation failed");
    }
}
Also used : LDAPException(com.unboundid.ldap.sdk.LDAPException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ResultCode(com.unboundid.ldap.sdk.ResultCode)

Example 35 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project oxTrust by GluuFederation.

the class AttributeImportAction method importAttributes.

public String importAttributes() throws Exception {
    if (!fileDataToImport.isReady()) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "File to import is invalid");
        return OxTrustConstants.RESULT_FAILURE;
    }
    ResultCode result = null;
    try (InputStream is = new ByteArrayInputStream(fileDataToImport.getData())) {
        result = ldifService.importLdifFileInLdap(GluuAttribute.class, is);
    } catch (LDAPException ex) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to import LDIF file");
    }
    removeFileToImport();
    if ((result != null) && result.equals(ResultCode.SUCCESS)) {
        facesMessages.add(FacesMessage.SEVERITY_INFO, "Attributes added successfully");
        return OxTrustConstants.RESULT_SUCCESS;
    } else {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to import LDIF file");
        return OxTrustConstants.RESULT_FAILURE;
    }
}
Also used : LDAPException(com.unboundid.ldap.sdk.LDAPException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ResultCode(com.unboundid.ldap.sdk.ResultCode) GluuAttribute(org.gluu.model.GluuAttribute)

Aggregations

LDAPException (com.unboundid.ldap.sdk.LDAPException)59 SearchResult (com.unboundid.ldap.sdk.SearchResult)15 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)13 SearchRequest (com.unboundid.ldap.sdk.SearchRequest)11 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)11 IOException (java.io.IOException)11 ResultCode (com.unboundid.ldap.sdk.ResultCode)9 LDIFReader (com.unboundid.ldif.LDIFReader)8 GeneralSecurityException (java.security.GeneralSecurityException)8 DN (com.unboundid.ldap.sdk.DN)6 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)5 Entry (com.unboundid.ldap.sdk.Entry)5 Filter (com.unboundid.ldap.sdk.Filter)5 LDAPConnectionPool (com.unboundid.ldap.sdk.LDAPConnectionPool)5 ArrayList (java.util.ArrayList)5 LdifDataUtility (org.gluu.persist.ldap.impl.LdifDataUtility)5 InMemoryDirectoryServer (com.unboundid.ldap.listener.InMemoryDirectoryServer)4 InMemoryDirectoryServerConfig (com.unboundid.ldap.listener.InMemoryDirectoryServerConfig)4 BindResult (com.unboundid.ldap.sdk.BindResult)4 SimpleBindRequest (com.unboundid.ldap.sdk.SimpleBindRequest)4