use of javax.naming.directory.DirContext in project hadoop by apache.
the class TestLdapGroupsMappingBase method setupMocksBase.
@Before
public void setupMocksBase() throws NamingException {
MockitoAnnotations.initMocks(this);
DirContext ctx = getContext();
doReturn(ctx).when(groupsMapping).getDirContext();
when(ctx.search(Mockito.anyString(), Mockito.anyString(), Mockito.any(Object[].class), Mockito.any(SearchControls.class))).thenReturn(userNames);
// We only ever call hasMoreElements once for the user NamingEnum, so
// we can just have one return value
when(userNames.hasMoreElements()).thenReturn(true);
SearchResult groupSearchResult = mock(SearchResult.class);
// We're going to have to define the loop here. We want two iterations,
// to get both the groups
when(groupNames.hasMoreElements()).thenReturn(true, true, false);
when(groupNames.nextElement()).thenReturn(groupSearchResult);
// Define the attribute for the name of the first group
Attribute group1Attr = new BasicAttribute("cn");
group1Attr.add(testGroups[0]);
Attributes group1Attrs = new BasicAttributes();
group1Attrs.put(group1Attr);
// Define the attribute for the name of the second group
Attribute group2Attr = new BasicAttribute("cn");
group2Attr.add(testGroups[1]);
Attributes group2Attrs = new BasicAttributes();
group2Attrs.put(group2Attr);
// This search result gets reused, so return group1, then group2
when(groupSearchResult.getAttributes()).thenReturn(group1Attrs, group2Attrs);
when(getUserNames().nextElement()).thenReturn(getUserSearchResult());
when(getUserSearchResult().getAttributes()).thenReturn(getAttributes());
// Define results for groups 1 level up
SearchResult parentGroupResult = mock(SearchResult.class);
// only one parent group
when(parentGroupNames.hasMoreElements()).thenReturn(true, false);
when(parentGroupNames.nextElement()).thenReturn(parentGroupResult);
// Define the attribute for the parent group
Attribute parentGroup1Attr = new BasicAttribute("cn");
parentGroup1Attr.add(testParentGroups[2]);
Attributes parentGroup1Attrs = new BasicAttributes();
parentGroup1Attrs.put(parentGroup1Attr);
// attach the attributes to the result
when(parentGroupResult.getAttributes()).thenReturn(parentGroup1Attrs);
when(parentGroupResult.getNameInNamespace()).thenReturn("CN=some_group,DC=test,DC=com");
}
use of javax.naming.directory.DirContext in project hadoop by apache.
the class LdapGroupsMapping method goUpGroupHierarchy.
/* Implementation for walking up the ldap hierarchy
* This function will iteratively find the super-group memebership of
* groups listed in groupDNs and add them to
* the groups set. It will walk up the hierarchy goUpHierarchy levels.
* Note: This is an expensive operation and settings higher than 1
* are NOT recommended as they will impact both the speed and
* memory usage of all operations.
* The maximum time for this function will be bounded by the ldap query
* timeout and the number of ldap queries that it will make, which is
* max(Recur Depth in LDAP, goUpHierarcy) * DIRECTORY_SEARCH_TIMEOUT
*
* @param ctx - The context for contacting the ldap server
* @param groupDNs - the distinguished name of the groups whose parents we
* want to look up
* @param goUpHierarchy - the number of levels to go up,
* @param groups - Output variable to store all groups that will be added
*/
void goUpGroupHierarchy(Set<String> groupDNs, int goUpHierarchy, Set<String> groups) throws NamingException {
if (goUpHierarchy <= 0 || groups.isEmpty()) {
return;
}
DirContext context = getDirContext();
Set<String> nextLevelGroups = new HashSet<String>();
StringBuilder filter = new StringBuilder();
filter.append("(&").append(groupSearchFilter).append("(|");
for (String dn : groupDNs) {
filter.append("(").append(groupMemberAttr).append("=").append(dn).append(")");
}
filter.append("))");
LOG.debug("Ldap group query string: " + filter.toString());
NamingEnumeration<SearchResult> groupResults = context.search(baseDN, filter.toString(), SEARCH_CONTROLS);
while (groupResults.hasMoreElements()) {
SearchResult groupResult = groupResults.nextElement();
getGroupNames(groupResult, groups, nextLevelGroups, true);
}
goUpGroupHierarchy(nextLevelGroups, goUpHierarchy - 1, groups);
}
use of javax.naming.directory.DirContext in project cachecloud by sohutv.
the class LoginUtil method passportCheck.
public static boolean passportCheck(String username, String password) {
//LDAP登陆地址
String ldapUrl = ConstUtils.LDAP_URL;
if (StringUtils.isBlank(ldapUrl)) {
logger.warn("ldap url is empty!!");
return true;
}
if (ConstUtils.IS_DEBUG) {
logger.warn("isDebug=true return");
return true;
}
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.provider.url", ldapUrl);
env.put("java.naming.security.authentication", "simple");
env.put("java.naming.security.principal", username + ConstUtils.EMAIL_SUFFIX);
env.put("java.naming.security.credentials", password);
DirContext ctx = null;
try {
ctx = new InitialDirContext(env);
if (ctx != null) {
return true;
}
} catch (Exception e) {
logger.error("username {} passportCheck: " + e.getMessage(), username, e);
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
return false;
}
use of javax.naming.directory.DirContext in project uPortal by Jasig.
the class LDAPGroupStore method searchForEntities.
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException {
if (type != group && type != iperson)
return new EntityIdentifier[0];
// Guarantee that LDAP injection is prevented by replacing LDAP special characters
// with escaped versions of the character
query = LdapEncoder.filterEncode(query);
ArrayList ids = new ArrayList();
switch(method) {
case STARTS_WITH:
query = query + "*";
break;
case ENDS_WITH:
query = "*" + query;
break;
case CONTAINS:
query = "*" + query + "*";
break;
}
query = namefield + "=" + query;
DirContext context = getConnection();
NamingEnumeration userlist = null;
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setReturningAttributes(new String[] { keyfield });
try {
userlist = context.search(usercontext, query, sc);
ArrayList keys = new ArrayList();
processLdapResults(userlist, keys);
String[] k = (String[]) keys.toArray(new String[0]);
for (int i = 0; i < k.length; i++) {
ids.add(new EntityIdentifier(k[i], iperson));
}
return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]);
} catch (NamingException nex) {
throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex);
}
}
use of javax.naming.directory.DirContext in project OpenAM by OpenRock.
the class Step4 method getLdapHostAndPort.
// Method to get hostname and port number with the
// provided Domain Name for Active Directory user data store.
private String[] getLdapHostAndPort(String domainName) throws NamingException, IOException {
if (!domainName.endsWith(".")) {
domainName += '.';
}
DirContext ictx = null;
// The resource record type A is defined in RFC 1035.
try {
Hashtable env = new Hashtable();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
ictx = new InitialDirContext(env);
Attributes attributes = ictx.getAttributes(domainName, new String[] { "A" });
Attribute attrib = attributes.get("A");
if (attrib == null) {
throw new NamingException();
}
} catch (NamingException e) {
// throw exception.
throw e;
}
// then look for the LDAP server
String serverHostName = null;
String serverPortStr = null;
final String ldapServer = "_ldap._tcp." + domainName;
try {
// Attempting to resolve ldapServer to SRV record.
// This is a mechanism defined in MSDN, querying
// SRV records for _ldap._tcp.DOMAINNAME.
// and get host and port from domain.
Attributes attributes = ictx.getAttributes(ldapServer, new String[] { "SRV" });
Attribute attr = attributes.get("SRV");
if (attr == null) {
throw new NamingException();
}
String[] srv = attr.get().toString().split(" ");
String hostNam = srv[3];
serverHostName = hostNam.substring(0, hostNam.length() - 1);
if ((serverHostName != null) && serverHostName.length() > 0) {
getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_HOST, serverHostName);
}
serverPortStr = srv[2];
} catch (NamingException e) {
// throw exception.
throw e;
}
// try to connect to LDAP port to make sure this machine
// has LDAP service
int serverPort = Integer.parseInt(serverPortStr);
if ((serverPort > 0) && (serverPort < 65535)) {
getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_PORT, serverPortStr);
}
try {
new Socket(serverHostName, serverPort).close();
} catch (IOException e) {
throw e;
}
String[] hostAndPort = new String[2];
hostAndPort[0] = serverHostName;
hostAndPort[1] = serverPortStr;
return hostAndPort;
}
Aggregations