//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected String bindDNAuthentication(javax.naming.ldap.InitialLdapContext paramInitialLdapContext, String paramString1, String paramString2, String paramString3, String paramString4) throws javax.naming.NamingException protected internal virtual string bindDNAuthentication(InitialLdapContext paramInitialLdapContext, string paramString1, string paramString2, string paramString3, string paramString4) { SearchControls searchControls = new SearchControls(); searchControls.SearchScope = 2; searchControls.ReturningAttributes = new string[0]; searchControls.TimeLimit = 5000; NamingEnumeration namingEnumeration = null; object[] arrayOfObject = new object[] { paramString1 }; namingEnumeration = paramInitialLdapContext.search(paramString3, paramString4, arrayOfObject, searchControls); if (!namingEnumeration.hasMore()) { namingEnumeration.close(); throw new NamingException("Search of baseDN(" + paramString3 + ") found no matches"); } SearchResult searchResult = (SearchResult)namingEnumeration.next(); string str1 = searchResult.Name; string str2 = null; if (searchResult.Relative == true) { str2 = str1 + "," + paramString3; } else { throw new NamingException("Can't follow referal for authentication: " + str1); } namingEnumeration.close(); namingEnumeration = null; InitialLdapContext initialLdapContext = constructInitialLdapContext(str2, paramString2); initialLdapContext.close(); return(str2); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public java.util.Collection findUserAndRoleDataByQuery(String paramString) throws javax.ejb.EJBException public virtual System.Collections.ICollection findUserAndRoleDataByQuery(string paramString) { LdapLoginUtil ldapLoginUtil = new LdapLoginUtil(Configuration.Options); List <object> arrayList = new List <object>(); try { InitialLdapContext initialLdapContext = ldapLoginUtil.makeLdapInitContext(); SearchControls searchControls = new SearchControls(); searchControls.SearchScope = 2; searchControls.ReturningAttributes = this.attrIDs; searchControls.TimeLimit = 10000; string str1 = Configuration.Options.get("rolesCtxDN").ToString(); string str2 = str1; if (Configuration.Options.get("rolesPlaceCtxDN") != null) { str2 = Configuration.Options.get("rolesPlaceCtxDN").ToString(); } string str3 = "(&(objectclass=person)(|(sAMAccountName=*" + paramString + "*)(name=*" + paramString + "*))(|(memberOf=CN=" + "CESAdmin" + "," + str2 + ")(memberOf=CN=" + "CESDatabaseUser" + "," + str2 + ")))"; NamingEnumeration namingEnumeration = initialLdapContext.search(str1, str3, searchControls); while (namingEnumeration.hasMoreElements()) { arrayList.Add(resultToUserRolesData((SearchResult)namingEnumeration.nextElement(), initialLdapContext, ldapLoginUtil, false)); } initialLdapContext.close(); } catch (Exception exception) { throw new EJBException(exception.Message); } return(arrayList); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public UserAndRolesData getUserAndRoleData(String paramString) throws javax.ejb.EJBException public virtual UserAndRolesData getUserAndRoleData(string paramString) { LdapLoginUtil ldapLoginUtil = new LdapLoginUtil(Configuration.Options); UserAndRolesData userAndRolesData = null; try { InitialLdapContext initialLdapContext = ldapLoginUtil.makeLdapInitContext(); SearchControls searchControls = new SearchControls(); searchControls.SearchScope = 2; searchControls.ReturningAttributes = this.attrIDs; searchControls.TimeLimit = 10000; string str1 = Configuration.Options.get("rolesCtxDN").ToString(); string str2 = "(&(objectclass=person)(sAMAccountName=" + paramString + "))"; NamingEnumeration namingEnumeration = initialLdapContext.search(str1, str2, searchControls); if (namingEnumeration.hasMoreElements()) { userAndRolesData = resultToUserRolesData((SearchResult)namingEnumeration.nextElement(), initialLdapContext, ldapLoginUtil, true); } else { throw new RemoteException(paramString + " was not found, it may have been deleted."); } initialLdapContext.close(); } catch (Exception exception) { Console.WriteLine(exception.ToString()); Console.Write(exception.StackTrace); throw new EJBException(exception.Message); } return(userAndRolesData); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public boolean checkUserExists(String paramString) throws javax.ejb.EJBException public virtual bool checkUserExists(string paramString) { bool @bool = false; LdapLoginUtil ldapLoginUtil = new LdapLoginUtil(Configuration.Options); try { InitialLdapContext initialLdapContext = ldapLoginUtil.makeLdapInitContext(); SearchControls searchControls = new SearchControls(); searchControls.SearchScope = 2; searchControls.ReturningAttributes = new string[0]; searchControls.TimeLimit = 10000; string str1 = Configuration.Options.get("rolesCtxDN").ToString(); string str2 = "(&(objectclass=person)(sAMAccountName=" + paramString + "))"; NamingEnumeration namingEnumeration = initialLdapContext.search(str1, str2, searchControls); if (namingEnumeration.hasMoreElements()) { @bool = true; } namingEnumeration.close(); initialLdapContext.close(); } catch (Exception exception) { throw new EJBException(exception.Message); } return(@bool); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAllowMultipleGroupMembershipAttributes() throws javax.naming.NamingException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldAllowMultipleGroupMembershipAttributes() { when(Config.get(SecuritySettings.ldap_authorization_user_search_filter)).thenReturn("{0}"); when(Config.get(SecuritySettings.ldap_authorization_group_membership_attribute_names)).thenReturn(asList("attr0", "attr1", "attr2")); when(Config.get(SecuritySettings.ldap_authorization_group_to_role_mapping)).thenReturn("group1=role1;group2=role2,role3"); LdapContext ldapContext = mock(typeof(LdapContext)); NamingEnumeration result = mock(typeof(NamingEnumeration)); SearchResult searchResult = mock(typeof(SearchResult)); Attributes attributes = mock(typeof(Attributes)); Attribute attribute1 = mock(typeof(Attribute)); Attribute attribute2 = mock(typeof(Attribute)); Attribute attribute3 = mock(typeof(Attribute)); NamingEnumeration attributeEnumeration = mock(typeof(NamingEnumeration)); NamingEnumeration groupEnumeration1 = mock(typeof(NamingEnumeration)); NamingEnumeration groupEnumeration2 = mock(typeof(NamingEnumeration)); NamingEnumeration groupEnumeration3 = mock(typeof(NamingEnumeration)); // Mock ldap search result "attr1" contains "group1" and "attr2" contains "group2" (a bit brittle...) // "attr0" is non-existing and should have no effect when(ldapContext.search(anyString(), anyString(), any(), any())).thenReturn(result); when(result.hasMoreElements()).thenReturn(true, false); when(result.next()).thenReturn(searchResult); when(searchResult.Attributes).thenReturn(attributes); when(attributes.All).thenReturn(attributeEnumeration); when(attributeEnumeration.hasMore()).thenReturn(true, true, false); when(attributeEnumeration.next()).thenReturn(attribute1, attribute2, attribute3); when(attribute1.ID).thenReturn("attr1"); // This attribute should yield role1 when(attribute1.All).thenReturn(groupEnumeration1); when(groupEnumeration1.hasMore()).thenReturn(true, false); when(groupEnumeration1.next()).thenReturn("group1"); when(attribute2.ID).thenReturn("attr2"); // This attribute should yield role2 and role3 when(attribute2.All).thenReturn(groupEnumeration2); when(groupEnumeration2.hasMore()).thenReturn(true, false); when(groupEnumeration2.next()).thenReturn("group2"); when(attribute3.ID).thenReturn("attr3"); // This attribute should have no effect when(attribute3.All).thenReturn(groupEnumeration3); when(groupEnumeration3.hasMore()).thenReturn(true, false); when(groupEnumeration3.next()).thenReturn("groupWithNoRole"); // When LdapRealm realm = new LdapRealm(Config, _securityLog, _secureHasher); ISet <string> roles = realm.FindRoleNamesForUser("username", ldapContext); // Then assertThat(roles, hasItems("role1", "role2", "role3")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWarnAboutGroupMembershipsBeingEmpty() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWarnAboutGroupMembershipsBeingEmpty() { when(Config.get(SecuritySettings.ldap_authorization_group_membership_attribute_names)).thenReturn(Collections.emptyList()); LdapContext ldapContext = mock(typeof(LdapContext)); NamingEnumeration result = mock(typeof(NamingEnumeration)); when(ldapContext.search(anyString(), anyString(), any(), any())).thenReturn(result); when(result.hasMoreElements()).thenReturn(false); assertException(this.makeAndInit, typeof(System.ArgumentException), "Illegal LDAP user search settings, see security log for details."); verify(_securityLog).error(contains("LDAP group membership attribute names are empty. " + "Authorization will not be possible.")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWarnAboutUserSearchBaseBeingEmpty() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWarnAboutUserSearchBaseBeingEmpty() { when(Config.get(SecuritySettings.ldap_authorization_user_search_base)).thenReturn(""); LdapContext ldapContext = mock(typeof(LdapContext)); NamingEnumeration result = mock(typeof(NamingEnumeration)); when(ldapContext.search(anyString(), anyString(), any(), any())).thenReturn(result); when(result.hasMoreElements()).thenReturn(false); assertException(this.makeAndInit, typeof(System.ArgumentException), "Illegal LDAP user search settings, see security log for details."); verify(_securityLog).error(contains("LDAP user search base is empty.")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWarnAboutUserSearchFilterWithoutArgument() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWarnAboutUserSearchFilterWithoutArgument() { when(Config.get(SecuritySettings.ldap_authorization_user_search_filter)).thenReturn(""); LdapContext ldapContext = mock(typeof(LdapContext)); NamingEnumeration result = mock(typeof(NamingEnumeration)); when(ldapContext.search(anyString(), anyString(), any(), any())).thenReturn(result); when(result.hasMoreElements()).thenReturn(false); MakeAndInit(); verify(_securityLog).warn(contains("LDAP user search filter does not contain the argument placeholder {0}")); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private java.util.Set<String> authorize(javax.naming.ldap.LdapContext ctx, String username) throws javax.naming.NamingException private ISet <string> Authorize(LdapContext ctx, string username) { ISet <string> roleNames = new LinkedHashSet <string>(); // Setup our search controls SearchControls searchCtls = new SearchControls(); searchCtls.SearchScope = SearchControls.SUBTREE_SCOPE; searchCtls.ReturningAttributes = new string[] { GROUP_ID }; // Use a search argument to prevent potential code injection object[] searchArguments = new object[] { username }; // Search for groups that has the user as a member NamingEnumeration result = ctx.search(GROUP_SEARCH_BASE, GROUP_SEARCH_FILTER, searchArguments, searchCtls); if (result.hasMoreElements()) { SearchResult searchResult = ( SearchResult )result.next(); Attributes attributes = searchResult.Attributes; if (attributes != null) { NamingEnumeration attributeEnumeration = attributes.All; while (attributeEnumeration.hasMore()) { Attribute attribute = ( Attribute )attributeEnumeration.next(); string attributeId = attribute.ID; if (attributeId.Equals(GROUP_ID, StringComparison.OrdinalIgnoreCase)) { // We found a group that the user is a member of. See if it has a role mapped to it string groupId = ( string )attribute.get(); string neo4jGroup = GetNeo4jRoleForGroupId(groupId); if (!string.ReferenceEquals(neo4jGroup, null)) { // Yay! Add it to our set of roles roleNames.Add(neo4jGroup); } } } } } return(roleNames); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private org.apache.shiro.authc.AuthenticationInfo queryForAuthenticationInfoSAM(org.apache.shiro.authc.AuthenticationToken token, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException private AuthenticationInfo QueryForAuthenticationInfoSAM(AuthenticationToken token, LdapContextFactory ldapContextFactory) { object principal = token.Principal; object credentials = token.Credentials; LdapContext ctx = null; try { ctx = _useStartTls ? GetSystemLdapContextUsingStartTls(ldapContextFactory) : ldapContextFactory.SystemLdapContext; string[] attrs = new string[] { "cn" }; SearchControls searchCtls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, attrs, false, false); object[] searchArguments = new object[] { principal }; string filter = "sAMAccountName={0}"; NamingEnumeration <SearchResult> search = ctx.search(_userSearchBase, filter, searchArguments, searchCtls); if (search.hasMore()) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.naming.directory.SearchResult next = search.next(); SearchResult next = search.next(); string loginUser = next.NameInNamespace; if (search.hasMore()) { _securityLog.error("More than one user matching: " + principal); throw new AuthenticationException("More than one user matching: " + principal); } else { LdapContext ctx2 = ldapContextFactory.getLdapContext(loginUser, credentials); LdapUtils.closeContext(ctx2); } } else { throw new AuthenticationException("No user matching: " + principal); } return(CreateAuthenticationInfo(token, principal, credentials, ctx)); } finally { LdapUtils.closeContext(ctx); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWarnAboutAmbiguousUserSearch() throws javax.naming.NamingException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWarnAboutAmbiguousUserSearch() { when(Config.get(SecuritySettings.ldap_authorization_user_search_filter)).thenReturn("{0}"); LdapContext ldapContext = mock(typeof(LdapContext)); NamingEnumeration result = mock(typeof(NamingEnumeration)); SearchResult searchResult = mock(typeof(SearchResult)); when(ldapContext.search(anyString(), anyString(), any(), any())).thenReturn(result); when(result.hasMoreElements()).thenReturn(true); when(result.next()).thenReturn(searchResult); when(searchResult.ToString()).thenReturn("<ldap search result>"); LdapRealm realm = new LdapRealm(Config, _securityLog, _secureHasher); realm.FindRoleNamesForUser("username", ldapContext); verify(_securityLog).warn(contains("LDAP user search for user principal 'username' is ambiguous")); }
// TODO: Extract to an LdapAuthorizationStrategy ? This ("group by attribute") is one of multiple possible strategies //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: java.util.Set<String> findRoleNamesForUser(String username, javax.naming.ldap.LdapContext ldapContext) throws javax.naming.NamingException internal virtual ISet <string> FindRoleNamesForUser(string username, LdapContext ldapContext) { ISet <string> roleNames = new LinkedHashSet <string>(); SearchControls searchCtls = new SearchControls(); searchCtls.SearchScope = SearchControls.SUBTREE_SCOPE; searchCtls.ReturningAttributes = _membershipAttributeNames.ToArray(); // Use search argument to prevent potential code injection object[] searchArguments = new object[] { username }; NamingEnumeration result = ldapContext.search(_userSearchBase, _userSearchFilter, searchArguments, searchCtls); if (result.hasMoreElements()) { SearchResult searchResult = ( SearchResult )result.next(); if (result.hasMoreElements()) { _securityLog.warn(_securityLog.DebugEnabled ? WithRealm("LDAP user search for user principal '%s' is ambiguous. The first match that will " + "be checked for group membership is '%s' but the search also matches '%s'. " + "Please check your LDAP realm configuration.", username, searchResult.ToString(), result.next().ToString()) : WithRealm("LDAP user search for user principal '%s' is ambiguous. The search matches more " + "than one entry. Please check your LDAP realm configuration.", username)); } Attributes attributes = searchResult.Attributes; if (attributes != null) { NamingEnumeration attributeEnumeration = attributes.All; while (attributeEnumeration.hasMore()) { Attribute attribute = ( Attribute )attributeEnumeration.next(); string attributeId = attribute.ID; if (_membershipAttributeNames.Any(attributeId.equalsIgnoreCase)) { ICollection <string> groupNames = LdapUtils.getAllAttributeValues(attribute); ICollection <string> rolesForGroups = GetRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return(roleNames); }
/// <exception cref="Javax.Naming.NamingException"/> internal virtual IList <string> DoGetGroups(string user) { IList <string> groups = new AList <string>(); DirContext ctx = GetDirContext(); // Search for the user. We'll only ever need to look at the first result NamingEnumeration <SearchResult> results = ctx.Search(baseDN, userSearchFilter, new object[] { user }, SearchControls); if (results.MoveNext()) { SearchResult result = results.Current; string userDn = result.GetNameInNamespace(); NamingEnumeration <SearchResult> groupResults = ctx.Search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))", new object[] { userDn }, SearchControls); while (groupResults.MoveNext()) { SearchResult groupResult = groupResults.Current; Attribute groupName = groupResult.GetAttributes().Get(groupNameAttr); groups.AddItem(groupName.Get().ToString()); } } return(groups); }
public virtual IList <Group> findGroupByQueryCriteria(LdapGroupQuery query) { ensureContextInitialized(); string groupBaseDn = composeDn(ldapConfiguration.GroupSearchBase, ldapConfiguration.BaseDn); if (ldapConfiguration.SortControlSupported) { applyRequestControls(query); } NamingEnumeration <SearchResult> enumeration = null; try { string filter = getGroupSearchFilter(query); enumeration = initialContext.search(groupBaseDn, filter, ldapConfiguration.SearchControls); // perform client-side paging int resultCount = 0; IList <Group> groupList = new List <Group>(); StringBuilder resultLogger = new StringBuilder(); if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append("LDAP group query results: ["); } while (enumeration.hasMoreElements() && groupList.Count < query.MaxResults) { SearchResult result = enumeration.nextElement(); GroupEntity group = transformGroup(result); string groupId = group.Id; if (string.ReferenceEquals(groupId, null)) { LdapPluginLogger.INSTANCE.invalidLdapGroupReturned(group, result); } else { if (isAuthorized(READ, GROUP, groupId)) { if (resultCount >= query.FirstResult) { if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append(group); resultLogger.Append(" based on "); resultLogger.Append(result); resultLogger.Append(", "); } groupList.Add(group); } resultCount++; } } } if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append("]"); LdapPluginLogger.INSTANCE.groupQueryResult(resultLogger.ToString()); } return(groupList); } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception) { // ignore silently } } }
public virtual IList <User> findUsersWithoutGroupId(LdapUserQueryImpl query, string userBaseDn, bool ignorePagination) { if (ldapConfiguration.SortControlSupported) { applyRequestControls(query); } NamingEnumeration <SearchResult> enumeration = null; try { string filter = getUserSearchFilter(query); enumeration = initialContext.search(userBaseDn, filter, ldapConfiguration.SearchControls); // perform client-side paging int resultCount = 0; IList <User> userList = new List <User>(); StringBuilder resultLogger = new StringBuilder(); if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append("LDAP user query results: ["); } while (enumeration.hasMoreElements() && (userList.Count < query.MaxResults || ignorePagination)) { SearchResult result = enumeration.nextElement(); UserEntity user = transformUser(result); string userId = user.Id; if (string.ReferenceEquals(userId, null)) { LdapPluginLogger.INSTANCE.invalidLdapUserReturned(user, result); } else { if (isAuthenticatedUser(user) || isAuthorized(READ, USER, userId)) { if (resultCount >= query.FirstResult || ignorePagination) { if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append(user); resultLogger.Append(" based on "); resultLogger.Append(result); resultLogger.Append(", "); } userList.Add(user); } resultCount++; } } } if (LdapPluginLogger.INSTANCE.DebugEnabled) { resultLogger.Append("]"); LdapPluginLogger.INSTANCE.userQueryResult(resultLogger.ToString()); } return(userList); } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception) { // ignore silently } } }
protected internal virtual IList <User> findUsersByGroupId(LdapUserQueryImpl query) { string baseDn = getDnForGroup(query.GroupId); // compose group search filter string groupSearchFilter = "(& " + ldapConfiguration.GroupSearchFilter + ")"; NamingEnumeration <SearchResult> enumeration = null; try { enumeration = initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.SearchControls); IList <string> groupMemberList = new List <string>(); // first find group while (enumeration.hasMoreElements()) { SearchResult result = enumeration.nextElement(); Attribute memberAttribute = result.Attributes.get(ldapConfiguration.GroupMemberAttribute); if (null != memberAttribute) { //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: javax.naming.NamingEnumeration<?> allMembers = memberAttribute.getAll(); NamingEnumeration <object> allMembers = memberAttribute.All; // iterate group members while (allMembers.hasMoreElements()) { groupMemberList.Add((string)allMembers.nextElement()); } } } IList <User> userList = new List <User>(); string userBaseDn = composeDn(ldapConfiguration.UserSearchBase, ldapConfiguration.BaseDn); int memberCount = 0; foreach (string memberId in groupMemberList) { if (userList.Count < query.MaxResults && memberCount >= query.FirstResult) { if (ldapConfiguration.UsePosixGroups) { query.userId(memberId); } IList <User> users = ldapConfiguration.UsePosixGroups ? findUsersWithoutGroupId(query, userBaseDn, true) : findUsersWithoutGroupId(query, memberId, true); if (users.Count > 0) { userList.Add(users[0]); } } memberCount++; } return(userList); } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception) { // ignore silently } } }