org.ldaptive.LdapException Java Examples

The following examples show how to use org.ldaptive.LdapException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapUserService.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticates the username and password using the LDAP/AD service. By default all the users
 * authenticated will have <b>USER</b> role. We might change this in future depending on the
 * attribute info available in the LDAP entries.
 *
 * @param userName ldap username
 * @param password ldap password
 * @param domain Auth domain.
 * @return {@link OneOpsUser} details object if successfully authenticated, else returns <code>
 *     null</code>.
 * @throws LdapException throws if any error authenticating/connecting to ldap server.
 */
public @Nullable OneOpsUser authenticate(String userName, char[] password, AuthDomain domain)
    throws LdapException {
  LdapEntry ldapUser =
      metricService.time("oneops.ldap.auth", () -> ldapClient.authenticate(userName, password));

  if (ldapUser != null) {
    String cn = getCommonName(ldapUser, userName);
    return new OneOpsUser(
        userName,
        String.valueOf(password),
        singletonList(new SimpleGrantedAuthority(USER.authority())),
        cn,
        domain);
  }
  return null;
}
 
Example #2
Source File: PrivilegedProvider.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Override
public ProviderConnection create() throws LdapException {
    final SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }

    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<ProviderConnection>() {
            @Override
            public ProviderConnection run() throws Exception {
                return new PrivilegedProviderConnection(delegate.create(), getProviderConfig());
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof LdapException) {
            throw (LdapException) e.getException();
        } else if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        } else {
            throw new RuntimeException(e.getException());
        }
    }
}
 
Example #3
Source File: LDAPAuthorizationBackend2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private String getRoleFromEntry(final Connection ldapConnection, final LdapName ldapName, final String role) {

        if (ldapName == null || Strings.isNullOrEmpty(role)) {
            return null;
        }

        if("dn".equalsIgnoreCase(role)) {
            return ldapName.toString();
        }

        try {
            final LdapEntry roleEntry = LdapHelper.lookup(ldapConnection, ldapName.toString());

            if(roleEntry != null) {
                final LdapAttribute roleAttribute = roleEntry.getAttribute(role);
                if(roleAttribute != null) {
                    return Utils.getSingleStringValue(roleAttribute);
                }
            }
        } catch (LdapException e) {
            log.error("Unable to handle role {} because of ",ldapName, e.toString(), e);
        }

        return null;
    }
 
Example #4
Source File: LDAPAuthenticationBackend2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private void authenticateByLdapServer(final Connection connection, final String dn, byte[] password)
        throws LdapException {
    final SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Response<Void>>() {
            @Override
            public Response<Void> run() throws LdapException {
                return connection.getProviderConnection().bind(new BindRequest(dn, new Credential(password)));
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof LdapException) {
            throw (LdapException) e.getException();
        } else if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example #5
Source File: MembershipSelector.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public LdapEntry next() {
  final String dn = dnsIterator.next();
  final SearchRequest request = new SearchRequest();
  request.setBaseDn(dn);
  request.setSearchFilter(usersFilter);
  request.setSearchScope(OBJECT);
  request.setReturnAttributes(returnAttrs);
  request.setSearchEntryHandlers(new ObjectGuidHandler());
  try {
    final Response<SearchResult> response = searchOp.execute(request);
    if (response.getResultCode() != SUCCESS) {
      throw new SyncException(
          format(
              "Couldn't get entry dn '%s', result code is '%s'", dn, response.getResultCode()));
    }
    return response.getResult().getEntry();
  } catch (LdapException x) {
    throw new SyncException(x.getLocalizedMessage(), x);
  }
}
 
Example #6
Source File: LDAPAuthorizationBackend.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private String getRoleFromEntry(final Connection ldapConnection, final LdapName ldapName, final String role) {

        if (ldapName == null || Strings.isNullOrEmpty(role)) {
            return null;
        }

        if("dn".equalsIgnoreCase(role)) {
            return ldapName.toString();
        }

        try {
            final LdapEntry roleEntry = LdapHelper.lookup(ldapConnection, ldapName.toString());

            if(roleEntry != null) {
                final LdapAttribute roleAttribute = roleEntry.getAttribute(role);
                if(roleAttribute != null) {
                    return Utils.getSingleStringValue(roleAttribute);
                }
            }
        } catch (LdapException e) {
            log.error("Unable to handle role {} because of ",ldapName, e.toString(), e);
        }

        return null;
    }
 
Example #7
Source File: ConnectionFactoryMonitor.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Gets a connection from the underlying connection factory and attempts to validate it.
 *
 * @return  Status with code {@link StatusCode#OK} on success otherwise {@link StatusCode#ERROR}.
 */
@Override
public Status observe() {
    Connection conn = null;
    try {
        conn = this.connectionFactory.getConnection();
        if (!conn.isOpen()) {
            conn.open();
        }
        return this.validator.validate(conn) ? OK : ERROR;
    } catch (final LdapException e) {
        logger.warn("Validation failed with error.", e);
    } finally {
        LdapUtils.closeConnection(conn);
    }
    return ERROR;
}
 
Example #8
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService rs) {
    if (rs.getId() != RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        return update(rs);
    }

    Connection connection = null;
    try {
        connection = getConnection();
        final AddOperation operation = new AddOperation(connection);

        final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
        operation.execute(new AddRequest(entry.getDn(), entry.getAttributes()));
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return rs;
}
 
Example #9
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public RegisteredService findServiceById(final long id) {
    Connection connection = null;
    try {
        connection = getConnection();

        final Response<SearchResult> response = searchForServiceById(connection, id);
        if (hasResults(response)) {
            return this.ldapServiceMapper.mapToRegisteredService(response.getResult().getEntry());
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }

    return null;
}
 
Example #10
Source File: LdaptiveResourceCRLFetcher.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Downloads a CRL from given LDAP url.
 *
 * @param r the resource that is the ldap url.
 * @return the x 509 cRL
 * @throws Exception if connection to ldap fails, or attribute to get the revocation list is unavailable
 */
protected X509CRL fetchCRLFromLdap(final Object r) throws Exception {
    try {
        final String ldapURL = r.toString();
        logger.debug("Fetching CRL from ldap {}", ldapURL);

        final Response<SearchResult> result = performLdapSearch(ldapURL);
        if (result.getResultCode() == ResultCode.SUCCESS) {
            final LdapEntry entry = result.getResult().getEntry();
            final LdapAttribute attribute = entry.getAttribute();

            logger.debug("Located entry [{}]. Retrieving first attribute [{}]",
                    entry, attribute);
            return fetchX509CRLFromAttribute(attribute);
        } else {
            logger.debug("Failed to execute the search [{}]", result);
        }

        throw new CertificateException("Failed to establish a connection ldap and search.");

    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
        throw new CertificateException(e);
    }
}
 
Example #11
Source File: ConnectionFactoryMonitor.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a connection from the underlying connection factory and attempts to validate it.
 *
 * @return  Status with code {@link StatusCode#OK} on success otherwise {@link StatusCode#ERROR}.
 */
@Override
public Status observe() {
    Connection conn = null;
    try {
        conn = this.connectionFactory.getConnection();
        if (!conn.isOpen()) {
            conn.open();
        }
        return this.validator.validate(conn) ? OK : ERROR;
    } catch (final LdapException e) {
        logger.warn("Validation failed with error.", e);
    } finally {
        LdapUtils.closeConnection(conn);
    }
    return ERROR;
}
 
Example #12
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService rs) {
    if (rs.getId() != RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        return update(rs);
    }

    Connection connection = null;
    try {
        connection = this.connectionFactory.getConnection();
        final AddOperation operation = new AddOperation(connection);

        final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
        operation.execute(new AddRequest(entry.getDn(), entry.getAttributes()));
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return rs;
}
 
Example #13
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public List<RegisteredService> load() {
    Connection connection = null;
    final List<RegisteredService> list = new LinkedList<RegisteredService>();
    try {
        connection = this.connectionFactory.getConnection();
        final Response<SearchResult> response =
                executeSearchOperation(connection, new SearchFilter(this.loadFilter));
        if (hasResults(response)) {
            for (final LdapEntry entry : response.getResult().getEntries()) {
                final RegisteredService svc = this.ldapServiceMapper.mapToRegisteredService(entry);
                list.add(svc);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return list;
}
 
Example #14
Source File: LdapAuthenticationHandler.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public String authenticate(String login, String password) throws AuthenticationException {

  final AuthenticationResponse response;
  try {
    LOG.debug("Attempting LDAP authentication for: {}", login);
    final AuthenticationRequest request =
        new AuthenticationRequest(login, new Credential(password));
    request.setReturnAttributes(returnAttributes);
    response = this.ldapAuthenticator.authenticate(request);
  } catch (final LdapException e) {
    throw new AuthenticationException(401, "Unexpected LDAP error");
  }
  LOG.debug("LDAP response: {}", response);

  if (!response.getResult()) {
    throw new AuthenticationException(
        401, "Authentication failed. Please check username and password.");
  }

  if (AuthenticationResultCode.DN_RESOLUTION_FAILURE == response.getAuthenticationResultCode()) {
    throw new AuthenticationException(login + "  is not found");
  }
  LOG.debug("Account state {}", response.getAccountState());
  return idNormalizer.retrieveAndNormalize(response.getLdapEntry());
}
 
Example #15
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public RegisteredService findServiceById(final long id) {
    Connection connection = null;
    try {
        connection = this.connectionFactory.getConnection();

        final Response<SearchResult> response = searchForServiceById(connection, id);
        if (hasResults(response)) {
            return this.ldapServiceMapper.mapToRegisteredService(response.getResult().getEntry());
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }

    return null;
}
 
Example #16
Source File: LdapUserDetailsService.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public OneOpsUser loadUserByUsername(String username) throws UsernameNotFoundException {
  try {
    List<X500Name> x500Names = ldapClient.searchUser(username);
    if (x500Names.size() == 0) {
      throw new UsernameNotFoundException("Can't load the user details for " + username);
    }
    X500Name x500Name = x500Names.get(0);
    List<SimpleGrantedAuthority> authorities =
        singletonList(new SimpleGrantedAuthority(USER.authority()));
    return new OneOpsUser(username, null, authorities, x500Name.getCommonName(), AuthDomain.PROD);

  } catch (IOException | LdapException e) {
    throw new UsernameNotFoundException("Can't load the user details for " + username, e);
  }
}
 
Example #17
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public List<RegisteredService> load() {
    Connection connection = null;
    final List<RegisteredService> list = new LinkedList<>();
    try {
        connection = getConnection();
        final Response<SearchResult> response =
                executeSearchOperation(connection, new SearchFilter(this.loadFilter));
        if (hasResults(response)) {
            for (final LdapEntry entry : response.getResult().getEntries()) {
                final RegisteredService svc = this.ldapServiceMapper.mapToRegisteredService(entry);
                list.add(svc);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return list;
}
 
Example #18
Source File: LookupSelector.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
private void requestNextPage() {
  try {
    response = prClient.execute(request, cm);
    if (response.getResultCode() != SUCCESS) {
      throw new SyncException(
          "Couldn't get a next page of entries, result code is " + response.getResultCode());
    }
    delegate = response.getResult().getEntries().iterator();
  } catch (LdapException x) {
    throw new SyncException(x.getLocalizedMessage(), x);
  }
}
 
Example #19
Source File: LdapAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential upc)
        throws GeneralSecurityException, PreventedException {
    final AuthenticationResponse response;
    try {
        logger.debug("Attempting LDAP authentication for {}", upc);
        final String password = getPasswordEncoder().encode(upc.getPassword());
        final AuthenticationRequest request = new AuthenticationRequest(upc.getUsername(),
                new org.ldaptive.Credential(password),
                this.authenticatedEntryAttributes);
        response = this.authenticator.authenticate(request);
    } catch (final LdapException e) {
        throw new PreventedException("Unexpected LDAP error", e);
    }
    logger.debug("LDAP response: {}", response);

    final List<MessageDescriptor> messageList;
    
    final LdapPasswordPolicyConfiguration ldapPasswordPolicyConfiguration =
            (LdapPasswordPolicyConfiguration) super.getPasswordPolicyConfiguration();
    if (ldapPasswordPolicyConfiguration != null) {
        logger.debug("Applying password policy to {}", response);
        messageList = ldapPasswordPolicyConfiguration.getAccountStateHandler().handle(
                response, ldapPasswordPolicyConfiguration);
    } else {
        messageList = Collections.emptyList();
    }
    
    if (response.getResult()) {
        return createHandlerResult(upc, createPrincipal(upc.getUsername(), response.getLdapEntry()), messageList);
    }

    if (AuthenticationResultCode.DN_RESOLUTION_FAILURE == response.getAuthenticationResultCode()) {
        throw new AccountNotFoundException(upc.getUsername() + " not found.");
    }
    throw new FailedLoginException("Invalid credentials");
}
 
Example #20
Source File: LdapSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param userUid The new user
 * @param userPassword The password for the new user
 * @param userGroup [optional] The group for the new user to be assigned to
 * @throws org.ldaptive.LdapException
 * @throws java.security.NoSuchAlgorithmException
 */
@When("^I create LDAP user '(.+?)' with password '(.+?)'( and assign it to LDAP group '(.+?)')?$")
public void createLDAPUser(String userUid, String userPassword, String userGroup) throws LdapException, NoSuchAlgorithmException {
    String userDn = "uid=" + userUid + "," + ThreadProperty.get("LDAP_USER_DN");
    int userUidNumber = this.commonspec.getLdapUtils().getLDAPMaxUidNumber() + 1;
    String groupName;
    if (userGroup == null) {
        groupName = "stratio";
    } else if (userGroup.equalsIgnoreCase("admin")) {
        groupName = ThreadProperty.get("LDAP_ADMIN_GROUP");
    } else {
        groupName = userGroup;
    }
    int groupGidNumber = this.commonspec.getLdapUtils().getLDAPgidNumber(groupName);
    this.assignLDAPuserToGroup(userUid, groupName);

    LdapEntry newUser = new LdapEntry(userDn);
    newUser.addAttribute(new LdapAttribute("objectClass", "inetOrgPerson", "posixAccount", "shadowAccount"));
    newUser.addAttribute(new LdapAttribute("cn", userUid));
    newUser.addAttribute(new LdapAttribute("sn", userUid));
    newUser.addAttribute(new LdapAttribute("gidNumber", String.valueOf(groupGidNumber)));
    newUser.addAttribute(new LdapAttribute("homeDirectory", "/home/" + userUid));
    newUser.addAttribute(new LdapAttribute("uidNumber", String.valueOf(userUidNumber)));
    newUser.addAttribute(new LdapAttribute("uid", userUid));
    this.commonspec.getLdapUtils().add(newUser);

    AttributeModification newAttr = new AttributeModification(AttributeModificationType.ADD, new LdapAttribute("userPassword", this.commonspec.getLdapUtils().hashPassword(userPassword)));
    this.commonspec.getLdapUtils().modify(userDn, newAttr);
}
 
Example #21
Source File: MessageDigestPasswordEncoder.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] digestCredential(Credential credential) throws LdapException {
    try {
        final MessageDigest md = MessageDigest.getInstance(algorithm);
        md.update(credential.getBytes());
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        throw new LdapException(e);
    }
}
 
Example #22
Source File: LdapAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential upc)
        throws GeneralSecurityException, PreventedException {
    final AuthenticationResponse response;
    try {
        logger.debug("Attempting LDAP authentication for {}", upc);
        final AuthenticationRequest request = new AuthenticationRequest(upc.getUsername(),
                new org.ldaptive.Credential(upc.getPassword()),
                this.authenticatedEntryAttributes);
        response = this.authenticator.authenticate(request);
    } catch (final LdapException e) {
        throw new PreventedException("Unexpected LDAP error", e);
    }
    logger.debug("LDAP response: {}", response);

    final List<Message> messageList;
    
    final LdapPasswordPolicyConfiguration ldapPasswordPolicyConfiguration =
            (LdapPasswordPolicyConfiguration) super.getPasswordPolicyConfiguration();
    if (ldapPasswordPolicyConfiguration != null) {
        logger.debug("Applying password policy to {}", response);
        messageList = ldapPasswordPolicyConfiguration.getAccountStateHandler().handle(
                response, ldapPasswordPolicyConfiguration);
    } else {
        messageList = Collections.emptyList();
    }
    
    if (response.getResult()) {
        return createHandlerResult(upc, createPrincipal(upc.getUsername(), response.getLdapEntry()), messageList);
    }

    if (AuthenticationResultCode.DN_RESOLUTION_FAILURE == response.getAuthenticationResultCode()) {
        throw new AccountNotFoundException(upc.getUsername() + " not found.");
    }
    throw new FailedLoginException("Invalid credentials.");
}
 
Example #23
Source File: LdapSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param userUid The user to change its password
 * @param newPassword The new password
 * @throws LdapException
 * @throws NoSuchAlgorithmException
 */
@When("^I change the password of LDAP user '(.+?)' to '(.+?)'$")
public void changeLDAPuserPassword(String userUid, String newPassword) throws LdapException, NoSuchAlgorithmException {
    String userDn = "uid=" + userUid + "," + ThreadProperty.get("LDAP_USER_DN");

    AttributeModification newAttr = new AttributeModification(AttributeModificationType.REPLACE, new LdapAttribute("userPassword", this.commonspec.getLdapUtils().hashPassword(newPassword)));
    this.commonspec.getLdapUtils().modify(userDn, newAttr);
}
 
Example #24
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private RegisteredService update(final RegisteredService rs) {
    Connection searchConnection = null;
    try {
        searchConnection = this.connectionFactory.getConnection();
        final Response<SearchResult> response = searchForServiceById(searchConnection, rs.getId());
        if (hasResults(response)) {
            final String currentDn = response.getResult().getEntry().getDn();

            Connection modifyConnection = null;
            try {
                modifyConnection = this.connectionFactory.getConnection();
                final ModifyOperation operation = new ModifyOperation(searchConnection);

                final List<AttributeModification> mods = new ArrayList<AttributeModification>();

                final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
                for (final LdapAttribute attr : entry.getAttributes()) {
                    mods.add(new AttributeModification(AttributeModificationType.REPLACE, attr));
                }
                final ModifyRequest request = new ModifyRequest(currentDn, mods.toArray(new AttributeModification[] {}));
                operation.execute(request);
            } finally {
                LdapUtils.closeConnection(modifyConnection);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(searchConnection);
    }
    return rs;
}
 
Example #25
Source File: PrivilegedProvider.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public Response<Void> bind(BindRequest request) throws LdapException {
    final SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }

    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<Response<Void>>() {
            @Override
            public Response<Void> run() throws Exception {
                if (jndiProviderConfig.getClassLoader() != null) {
                    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

                    try {
                        Thread.currentThread().setContextClassLoader(jndiProviderConfig.getClassLoader());
                        return delegate.bind(request);
                    } finally {
                        Thread.currentThread().setContextClassLoader(originalClassLoader);
                    }
                } else {
                    return delegate.bind(request);
                }
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof LdapException) {
            throw (LdapException) e.getException();
        } else if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        } else {
            throw new RuntimeException(e.getException());
        }
    }
}
 
Example #26
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private Response<SearchResult> searchForServiceById(final Connection connection, final long id)
        throws LdapException {

    final SearchFilter filter = new SearchFilter(this.searchFilter);
    filter.setParameter(0, id);
    return executeSearchOperation(connection, filter);
}
 
Example #27
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private Response<SearchResult> executeSearchOperation(final Connection connection, final SearchFilter filter)
        throws LdapException {

    final SearchOperation searchOperation = new SearchOperation(connection);
    final SearchRequest request = newRequest(filter);
    logger.debug("Using search request {}", request.toString());
    return searchOperation.execute(request);
}
 
Example #28
Source File: LdapTestUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the given LDAP entries.
 *
 * @param connection Open LDAP connection used to connect to directory.
 * @param entries Collection of LDAP entries.
 */
public static void removeLdapEntries(final Connection connection, final Collection<LdapEntry> entries) {
    for (final LdapEntry entry : entries) {
        try {
            new DeleteOperation(connection).execute(new DeleteRequest(entry.getDn()));
        } catch (final LdapException e) {
            LOGGER.warn("LDAP error removing entry {}", entry, e);
        }
    }
}
 
Example #29
Source File: LoginAuthProvider.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Performs authentication.
 *
 * @param auth UsernamePasswordAuthenticationToken.
 * @return authenticated object.
 * @throws AuthenticationException if authentication fails.
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
  Assert.notNull(auth, "No authentication data provided.");
  String userName = (String) auth.getPrincipal();
  String password = (String) auth.getCredentials();
  AuthDomain domain = (AuthDomain) auth.getDetails();

  OneOpsUser user = null;
  try {
    user = ldapUserService.authenticate(userName, password.toCharArray(), domain);
  } catch (LdapException ex) {
    log.debug("Ldap Authentication failed for user: " + userName, ex);
  }

  if (user == null) {
    throw new BadCredentialsException("Invalid Username/Password.");
  }

  // Check for user privileges.
  if (user.getAuthorities().isEmpty()) {
    throw new InsufficientAuthenticationException(
        user.getUsername() + " user has no roles assigned.");
  }

  return new LoginAuthToken(user, null, user.getAuthorities());
}
 
Example #30
Source File: LdapSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param groupCn The new group
 * @throws LdapException
 * @throws NoSuchAlgorithmException
 */
@When("^I create LDAP group '(.+?)'$")
public void createLDAPGroup(String groupCn) throws LdapException {
    String groupDn = "cn=" + groupCn + "," + ThreadProperty.get("LDAP_GROUP_DN");
    int groupGidNumber = this.commonspec.getLdapUtils().getLDAPMaxGidNumber() + 1;

    LdapEntry newGroup = new LdapEntry(groupDn);
    newGroup.addAttribute(new LdapAttribute("objectClass", "groupOfNames", "posixGroup"));
    newGroup.addAttribute(new LdapAttribute("cn", groupCn));
    newGroup.addAttribute(new LdapAttribute("gidNumber", String.valueOf(groupGidNumber)));
    newGroup.addAttribute(new LdapAttribute("member", "uid=fake," + ThreadProperty.get("LDAP_USER_DN")));
    newGroup.addAttribute(new LdapAttribute("description", groupCn + " group"));
    newGroup.addAttribute(new LdapAttribute("memberUid", "uid=fake," + ThreadProperty.get("LDAP_USER_DN")));
    this.commonspec.getLdapUtils().add(newGroup);
}