public DirContextOperations authenticate(Authentication authentication) {
		DirContextOperations user = null;
		Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
				"Can only process UsernamePasswordAuthenticationToken objects");

		String username = authentication.getName();
		String password = (String) authentication.getCredentials();

		if (!StringUtils.hasLength(password)) {
			logger.debug("Rejecting empty password for user " + username);
			throw new BadCredentialsException(messages.getMessage(
					"BindAuthenticator.emptyPassword", "Empty Password"));
		}

		// If DN patterns are configured, try authenticating with them directly
		for (String dn : getUserDns(username)) {
			user = bindWithDn(dn, username, password);

			if (user != null) {
				break;
			}
		}

		// Otherwise use the configured search object to find the user and authenticate
		// with the returned DN.
		if (user == null && getUserSearch() != null) {
			DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
			user = bindWithDn(userFromSearch.getDn().toString(), username, password,
					userFromSearch.getAttributes());
		}

		if (user == null) {
			throw new BadCredentialsException(messages.getMessage(
					"BindAuthenticator.badCredentials", "Bad credentials"));
		}

		return user;
	}