//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); }
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 } } }