下面列出了javax.naming.directory.SearchControls#setSearchScope ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reused method to search groups with various filters.
*
* @param searchFilter
* @param returningAttributes
* @param searchScope
* @return
*/
protected NamingEnumeration<SearchResult> searchInGroupBase(String searchFilter,
String[] returningAttributes,
int searchScope,
DirContext rootContext,
String searchBase)
throws UserStoreException {
SearchControls userSearchControl = new SearchControls();
userSearchControl.setReturningAttributes(returningAttributes);
userSearchControl.setSearchScope(searchScope);
NamingEnumeration<SearchResult> groupSearchResults = null;
try {
groupSearchResults = rootContext.search(escapeDNForSearch(searchBase), searchFilter, userSearchControl);
} catch (NamingException e) {
String errorMessage = "Error occurred while searching in group base.";
if (log.isDebugEnabled()) {
log.debug(errorMessage, e);
}
throw new UserStoreException(errorMessage, e);
}
return groupSearchResults;
}
/**
* Creates a simple LDAP connector using the given configuration. Throws a
* NullPointerException if the specified URL is null or empty.
*
* TODO: parameters
*/
public SimpleLdapConnector(String url, String context, String user,
String password, boolean readOnly) {
fUrl = url;
if (fUrl == null || fUrl.isEmpty()) {
throw new NullPointerException("no URL given");
}
if (context == null) {
fUserContext = "";
} else {
fUserContext = "," + context;
}
fUser = user;
fPassword = password.toCharArray();
fReadOnly = readOnly;
fCtrl = new SearchControls();
fCtrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
/**
* Retrieves a list of all groups the user is a member of.
* @param dirContext a DirContext
* @param ldapUser the LdapUser to retrieve group membership for
* @return A list of Strings representing the fully qualified DN of each group
* @throws NamingException if an exception is thrown
* @since 1.4.0
*/
public List<String> getGroups(final DirContext dirContext, final LdapUser ldapUser) throws NamingException {
LOGGER.debug("Retrieving groups for: " + ldapUser.getDN());
final List<String> groupDns = new ArrayList<>();
final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser);
final SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc);
while (hasMoreEnum(ne)) {
final SearchResult result = ne.next();
groupDns.add(result.getNameInNamespace());
LOGGER.debug("Found group: " + result.getNameInNamespace() + " for user: " + ldapUser.getDN());
}
closeQuietly(ne);
return groupDns;
}
private static SearchControls createSearchControl(final boolean recursive, final String[] attributes) {
if (SECURITY_LOGGER.isTraceEnabled()) {
SECURITY_LOGGER.tracef("createSearchControl recursive=%b, attributes=%s", recursive, Arrays.toString(attributes));
}
// 2 - Search to identify the DN of the user connecting
SearchControls searchControls = new SearchControls();
if (recursive) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(attributes);
searchControls.setTimeLimit(searchTimeLimit);
return searchControls;
}
/**
* Find the user dn with its uid
*
* @param uid
* @param ctx
* @return user's dn
*/
private String searchUserDN(final String uid, final DirContext ctx) {
if (ctx == null) {
return null;
}
final List<String> ldapBases = LDAPLoginModule.getLdapBases();
final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
final String[] serachAttr = { "dn" };
final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
final SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setReturningAttributes(serachAttr);
String userDN = null;
for (final String ldapBase : ldapBases) {
try {
final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
while (enm.hasMore()) {
final SearchResult result = enm.next();
userDN = result.getNameInNamespace();
}
if (userDN != null) {
break;
}
} catch (final NamingException e) {
log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
}
}
return userDN;
}
private NamingEnumeration<SearchResult> searchGroupMembership(String user, DirContext context)
throws NamingException
{
String userBase = userBaseDistinguishedName.get();
String searchFilter = replaceUser(groupAuthorizationSearchPattern.get(), user);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
return context.search(userBase, searchFilter, searchControls);
}
public void testSearchNotFilter() throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
searchControls.setReturningAttributes(new String[]{"mail"});
NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(!(objectclass=test))", searchControls);
searchResults.close();
}
@Test
public void testDirContext() throws Exception {
// Test using the good ol' JDNI-LDAP integration
final DirContext dirContext = embeddedLdapRule.dirContext();
final SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
final NamingEnumeration<javax.naming.directory.SearchResult> resultNamingEnumeration =
dirContext.search(DOMAIN_DSN, "(objectClass=person)", searchControls);
assertEquals(24, Iterators.size(Iterators.forEnumeration(resultNamingEnumeration)));
}
@Test
public void testSearchProcessor() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
DummyDirContextProcessor processor = new DummyDirContextProcessor();
List<String> cns = ldapTemplate.search("", "(&(objectclass=person)(sn=Person3))", searchControls,
new CnContextMapper(), processor);
assertThat(cns).hasSize(1);
assertThat(cns.get(0)).isEqualTo("Some Person3");
assertThat(processor.isPreProcessCalled()).isTrue();
assertThat(processor.isPostProcessCalled()).isTrue();
}
@Test
public void startLdapServer() throws Exception {
DirContext ctx = createContext();
Assert.assertNotNull(ctx);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);
int count = 0;
while (result.hasMore()) {
result.next();
count++;
}
String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();
System.out.println("======================================================");
System.out.println("LDAP server started successfully.");
System.out.println("");
System.out.println(" URL: " + url);
System.out.println(" Node Count: " + count);
System.out.println(" Direct Bind DN: cn=${username},ou=developers,ou=people,o=apiman");
System.out.println("======================================================");
System.out.println("");
System.out.println("");
System.out.println("Press Enter to stop the LDAP server.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Shutting down the LDAP server...");
}
NotifierArgs(String name, int scope, NamingListener l) {
this(name, "(objectclass=*)", null, l);
// if scope is not default, create search ctl and set it
if (scope != EventContext.ONELEVEL_SCOPE) {
controls = new SearchControls();
controls.setSearchScope(scope);
}
}
/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
List<String> userList = new ArrayList<>();
String userDnTemplate = r.getUserDnTemplate();
String userDn[] = userDnTemplate.split(",", 2);
String userDnPrefix = userDn[0].split("=")[0];
String userDnSuffix = userDn[1];
JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = cf.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setCountLimit(numUsersToFetch);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {userDnPrefix};
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result =
ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userDnPrefix) != null) {
String currentUser = attrs.get(userDnPrefix).toString();
userList.add(currentUser.split(":")[1].trim());
}
}
} catch (Exception e) {
LOGGER.error("Error retrieving User list from Ldap Realm", e);
}
LOGGER.info("UserList: " + userList);
return userList;
}
/**
* For a given name, this method makes ldap search in userBase with filter {@link LdapRepositoryConfiguration#userIdAttribute}=name
* and objectClass={@link LdapRepositoryConfiguration#userObjectClass} and builds {@link User} based on search result.
*
* @param name
* The userId which should be value of the field {@link LdapRepositoryConfiguration#userIdAttribute}
* @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
* userId of this user and ldap connection information with which
* the user was searched. Return null if such a user was not found.
* @throws NamingException
* Propagated by the underlying LDAP communication layer.
*/
private ReadOnlyLDAPUser searchAndBuildUser(Username name) throws NamingException {
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setReturningAttributes(new String[] { ldapConfiguration.getUserIdAttribute() });
sc.setCountLimit(1);
String filterTemplate = "(&({0}={1})(objectClass={2})" +
StringUtils.defaultString(ldapConfiguration.getFilter(), "") +
")";
String sanitizedFilter = FilterEncoder.format(
filterTemplate,
ldapConfiguration.getUserIdAttribute(),
name.asString(),
ldapConfiguration.getUserObjectClass());
NamingEnumeration<SearchResult> sr = ldapContext.search(ldapConfiguration.getUserBase(), sanitizedFilter, sc);
if (!sr.hasMore()) {
return null;
}
SearchResult r = sr.next();
Attribute userName = r.getAttributes().get(ldapConfiguration.getUserIdAttribute());
if (!ldapConfiguration.getRestriction().isActivated()
|| userInGroupsMembershipList(r.getNameInNamespace(), ldapConfiguration.getRestriction().getGroupMembershipLists(ldapContext))) {
return new ReadOnlyLDAPUser(Username.of(userName.get().toString()), r.getNameInNamespace(), ldapContext);
}
return null;
}
@Test
public void testSearch_String_SearchControls_ContextMapper_ReturningObjFlagNotSet() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
SearchControls expectedControls = new SearchControls();
expectedControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
expectedControls.setReturningObjFlag(true);
Object expectedObject = new Object();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
singleSearchResultWithStringBase(expectedControls, searchResult);
Object expectedResult = expectedObject;
when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
/**
* Looks up an LDAP object by its DN and returns {@code true} if
* the search was successful.
*
* @param ctx the Context to use for the lookup.
* @param dn the object's dn to lookup.
* @return true if the lookup was successful.
* @throws NamingException if login credentials were wrong.
*/
private Boolean lookupExistence(InitialDirContext ctx, LdapName dn, String[] returnattrs) throws NamingException {
Log.debug("In lookupExistence(ctx, dn, returnattrs), searchdn is: {}", dn);
// Bind to the object's DN
ctx.addToEnvironment(Context.PROVIDER_URL, getProviderURL(dn));
String filter = "(&(objectClass=*))";
SearchControls srcnt = new SearchControls();
srcnt.setSearchScope(SearchControls.OBJECT_SCOPE);
srcnt.setReturningAttributes(returnattrs);
NamingEnumeration<SearchResult> answer = null;
try {
answer = ctx.search(
"",
filter,
srcnt);
} catch (javax.naming.NameNotFoundException nex) {
Log.debug("Unable to find ldap object {}.", dn);
}
if (answer == null || !answer.hasMoreElements())
{
Log.debug(".... lookupExistence: DN not found.");
return false;
}
else
{
Log.debug(".... lookupExistence: DN found.");
return true;
}
}
/**
* Creates a connnection to a directory.
*
* @param parameters parameters to establish connection.
*/
public LdapConnection(ConnectionParameters parameters) {
super(Driver.DIALECT, parameters);
Hashtable<String, Object> env = new Hashtable<String, Object>();
//Put default settings
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//Put connection settings
if (parameters.getUrl() == null) {
throw new LdapProviderException("Connection URL is required");
}
env.put(Context.PROVIDER_URL, parameters.getUrl());
if (parameters.getUser() != null) {
env.put(Context.SECURITY_PRINCIPAL, parameters.getUser());
}
if (parameters.getPassword() != null) {
env.put(Context.SECURITY_CREDENTIALS, parameters.getPassword());
}
//Override env with user specified connection properties
env.putAll(parameters.getProperties());
//Set the search controls used for queries
searchControls = new SearchControls();
String scope = parameters.getStringProperty(SEARCH_SCOPE_KEY);
if (scope != null) {
if ("object".equalsIgnoreCase(scope)) {
searchControls.setSearchScope(SearchControls.OBJECT_SCOPE);
} else if ("onelevel".equalsIgnoreCase(scope)) {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
} else if ("subtree".equalsIgnoreCase(scope)) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
throw new LdapProviderException("Unsupported " + SEARCH_SCOPE_KEY + "=" + scope);
}
}
String baseDn = parameters.getStringProperty(SEARCH_BASEDN_KEY);
this.baseDn = baseDn == null ? "" : baseDn;
Integer tl = parameters.getIntegerProperty(SEARCH_TIMELIMIT_KEY);
if (tl != null) {
searchControls.setTimeLimit(tl);
}
Integer cl = parameters.getIntegerProperty(SEARCH_COUNTLIMIT_KEY);
if (cl != null) {
searchControls.setCountLimit(cl);
}
Number mfl = parameters.getNumberProperty(FILE_MAXLENGTH_KEY, null);
maxFileLength = mfl == null ? null : mfl.longValue();
driverContext = parameters.getContext();
initializeContext(env); //Initializing context
}
protected SearchControls createSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
return searchControls;
}
private String getNameFromId(final String id, final Subject gssapiIdentity)
throws NamingException
{
if (!isBindWithoutSearch())
{
InitialDirContext ctx = createSearchInitialDirContext(gssapiIdentity);
try
{
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(new String[]{});
searchControls.setCountLimit(1L);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
LOGGER.debug("Searching for '{}'", id);
NamingEnumeration<?> namingEnum = invokeContextOperationAs(gssapiIdentity,
(PrivilegedExceptionAction<NamingEnumeration<?>>) () -> ctx.search(
_searchContext,
_searchFilter,
new String[]{id},
searchControls));
if (namingEnum.hasMore())
{
SearchResult result = (SearchResult) namingEnum.next();
String name = result.getNameInNamespace();
LOGGER.debug("Found '{}' DN '{}'", id, name);
return name;
}
else
{
LOGGER.debug("Not found '{}'", id);
return null;
}
}
finally
{
closeSafely(ctx);
}
}
else
{
return id;
}
}
@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context, Long domainId) throws NamingException, IOException {
final SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(_ldapConfiguration.getScope());
searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));
String basedn = _ldapConfiguration.getBaseDn(domainId);
if (StringUtils.isBlank(basedn)) {
throw new IllegalArgumentException(String.format("ldap basedn is not configured (for domain: %s)", domainId));
}
byte[] cookie = null;
int pageSize = _ldapConfiguration.getLdapPageSize(domainId);
context.setRequestControls(new Control[]{new PagedResultsControl(pageSize, Control.NONCRITICAL)});
final List<LdapUser> users = new ArrayList<LdapUser>();
NamingEnumeration<SearchResult> results;
do {
results = context.search(basedn, generateSearchFilter(username, domainId), searchControls);
while (results.hasMoreElements()) {
final SearchResult result = results.nextElement();
if (!isUserDisabled(result)) {
users.add(createUser(result, domainId));
}
}
Control[] contextControls = context.getResponseControls();
if (contextControls != null) {
for (Control control : contextControls) {
if (control instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
cookie = prrc.getCookie();
}
}
} else {
LOGGER.info("No controls were sent from the ldap server");
}
context.setRequestControls(new Control[] {new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
} while (cookie != null);
return users;
}
/**
* Check if the given DN matches the group search filter
*
* @param dn the absolute DN of the node to check
* @return true if the given DN is matching the group filter. false oterwise.
* @throws NamingException if the search for the dn fails.
*/
public boolean isGroupDN(LdapName dn) throws NamingException {
Log.debug("LdapManager: Trying to check if DN is a group. DN: {}, Base DN: {} ...", dn, baseDN);
// is it a sub DN of the base DN?
if (!dn.startsWith(baseDN)
&& (alternateBaseDN == null || !dn.startsWith(alternateBaseDN))) {
if (Log.isDebugEnabled()) {
Log.debug("LdapManager: DN ({}) does not fit to baseDN ({},{})", dn, baseDN, alternateBaseDN);
}
return false;
}
DirContext ctx = null;
try {
Log.debug("LdapManager: Starting LDAP search to check group DN: {}", dn);
// Search for the group in the node with the given DN.
// should return the group object itself if is matches the group filter
ctx = getContext(dn);
// only search the object itself.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
constraints.setReturningAttributes(new String[]{});
String filter = MessageFormat.format(getGroupSearchFilter(), "*");
NamingEnumeration<SearchResult> answer = ctx.search("", filter, constraints);
Log.debug("LdapManager: ... group check search finished for DN: {}", dn);
boolean result = (answer != null && answer.hasMoreElements());
if (answer != null) {
answer.close();
}
Log.debug("LdapManager: DN is group: {}? {}!", dn, result);
return result;
}
catch (final Exception e) {
Log.debug("LdapManager: Exception thrown when checking if DN is a group {}", dn, e);
throw e;
}
finally {
try {
if (ctx != null)
ctx.close();
}
catch (Exception ex) {
Log.debug("An exception occurred while trying to close a LDAP context after trying to verify that DN '{}' is a group.", dn, ex);
}
}
}