protected internal virtual void ensureContextInitialized() { if (initialContext == null) { initialContext = openContext(ldapConfiguration.ManagerDn, ldapConfiguration.ManagerPassword); } }
public void Main( [Option("organization_code", "organization code")] int organizationCode ) { _logger.LogInformation($"{GetType().FullName} Start"); try { var domainSets = _configuration.GetSection("ActiveDirectorySync") .Get <List <OrganizationDomainSet> >() .Where(d => d.OrganizationCode == organizationCode); foreach (var organizationDomain in domainSets) { _logger.LogDebug($"{organizationDomain.OrganizationCode} {organizationDomain.DomainName}"); var ldapContext = new LdapContext(organizationDomain.LdapConfig.Server, organizationDomain.LdapConfig.Port, organizationDomain.LdapConfig.DomainAndUser, organizationDomain.LdapConfig.Password); var ldapRepository = new LdapRepository(ldapContext); DoIt(ldapRepository, organizationDomain.OrganizationCode, organizationDomain.DomainName, organizationDomain.DeviceGroupObjectGuidArray, organizationDomain.UserGroupObjectGuidArray); } _logger.LogInformation($"{GetType().FullName} Success"); } catch (Exception e) { _logger.LogError(e.Message, e); _logger.LogInformation($"{GetType().FullName} Error"); } }
public LdapUserConfig(string id, DbContext context) { ldapContext = new LdapContext(context); dirContext = new DivisionDirectoryContext(); this.Member = dirContext.DirectoryMembers.GetByID(id); if (this.Member == null) throw new Exception(string.Format("No member with ID {0} was found in the directory", id)); this.Context = context; this.LdapConfig = ldapContext.LdapConfigs.First(); List<OuAssignment> ous = ldapContext.OuAssignments.Get(x => (x.MembershipScope & this.Member.MembershipScope) == x.MembershipScope).ToList(); if (ous.Count == 0) throw new Exception("There are no OU's assigned to this user filter"); if (ous.Count() > 1) throw new Exception("This member applies to multiple OU Assignments. Please consider refining your filter criteria"); OuAssignment = ous.First(); List<GroupAssignmentConfig> cfgs = ldapContext.GroupAssignmentConfigs.Get().ToList(); this.GroupConfigs = new List<GroupAssignmentConfig>(); foreach (GroupAssignmentConfig cfg in cfgs) { List<DirectoryMember> members = dirContext.DirectoryMembers.GetByFilter(cfg.MembershipScope, null); if (members.FirstOrDefault(x => x.InternalId == Member.InternalId) != null) GroupConfigs.Add(cfg); } this.PersonalFolders = new List<PersonalFolder>(); List<PersonalFolder> fldrs = ldapContext.PersonalFolders.Get().ToList(); foreach (PersonalFolder f in fldrs) { List<DirectoryMember> members = dirContext.DirectoryMembers.GetByFilter(f.MembershipScope, null); if (members.FirstOrDefault(x => x.InternalId == Member.InternalId) != null) PersonalFolders.Add(f); } string pwd = ldapContext.LdapConfigs.Decryptpassword(LdapConfig); PrincipalContext = new PrincipalContext(ContextType.Domain, LdapConfig.DomainPrincipalName, LdapConfig.UserName, pwd); ExistsInLdap = GetExistsInLdap(); if (GetExistsInLdap()) LdapUser = UserPrincipal.FindByIdentity(PrincipalContext, IdentityType.SamAccountName, Member.UserName); }
//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 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 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}")); }
// ===== Helpers ===== //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void modifyLDAPAttribute(String username, Object credentials, String attribute, Object value) throws Throwable private void ModifyLDAPAttribute(string username, object credentials, string attribute, object value) { string principal = string.Format("cn={0},ou=users,dc=example,dc=com", username); string principal1 = string.Format("cn={0},ou=users,dc=example,dc=com", username); JndiLdapContextFactory contextFactory = new JndiLdapContextFactory(); contextFactory.Url = "ldaps://localhost:10636"; LdapContext ctx = contextFactory.getLdapContext(principal1, credentials); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(attribute, value)); // Perform the update ctx.modifyAttributes(principal, mods); ctx.close(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public org.neo4j.server.security.enterprise.auth.plugin.spi.AuthInfo authenticateAndAuthorize(org.neo4j.server.security.enterprise.auth.plugin.api.AuthToken authToken) throws org.neo4j.server.security.enterprise.auth.plugin.api.AuthenticationException public override AuthInfo AuthenticateAndAuthorize(AuthToken authToken) { try { string username = authToken.Principal(); char[] password = authToken.Credentials(); LdapContext ctx = Authenticate(username, password); ISet <string> roles = Authorize(ctx, username); return(AuthInfo.of(username, roles)); } catch (NamingException e) { throw new AuthenticationException(e.Message); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected org.apache.shiro.authc.AuthenticationInfo queryForAuthenticationInfoUsingStartTls(org.apache.shiro.authc.AuthenticationToken token, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException protected internal virtual AuthenticationInfo QueryForAuthenticationInfoUsingStartTls(AuthenticationToken token, LdapContextFactory ldapContextFactory) { object principal = getLdapPrincipal(token); object credentials = token.Credentials; LdapContext ctx = null; try { ctx = GetLdapContextUsingStartTls(ldapContextFactory, principal, credentials); return(CreateAuthenticationInfo(token, principal, credentials, ctx)); } finally { LdapUtils.closeContext(ctx); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected org.apache.shiro.authz.AuthorizationInfo queryForAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection principals, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException protected internal override AuthorizationInfo QueryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) { if (_authorizationEnabled.Value) { string username = GetUsername(principals); if (string.ReferenceEquals(username, null)) { return(null); } if (_useSystemAccountForAuthorization.Value) { // Perform context search using the system context LdapContext ldapContext = _useStartTls ? GetSystemLdapContextUsingStartTls(ldapContextFactory) : ldapContextFactory.SystemLdapContext; ISet <string> roleNames; try { roleNames = FindRoleNamesForUser(username, ldapContext); } finally { LdapUtils.closeContext(ldapContext); } return(new SimpleAuthorizationInfo(roleNames)); } else { // Authorization info is cached during authentication Cache <object, AuthorizationInfo> authorizationCache = AuthorizationCache; AuthorizationInfo authorizationInfo = authorizationCache.get(username); if (authorizationInfo == null) { // The cached authorization info has expired. // Since we do not have the subject's credentials we cannot perform a new LDAP search // for authorization info. Instead we need to fail with a special status, // so that the client can react by re-authenticating. throw new AuthorizationExpiredException("LDAP authorization info expired."); } return(authorizationInfo); } } return(null); }
//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); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private javax.naming.ldap.LdapContext getLdapContextUsingStartTls(org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory, Object principal, Object credentials) throws javax.naming.NamingException private LdapContext GetLdapContextUsingStartTls(LdapContextFactory ldapContextFactory, object principal, object credentials) { JndiLdapContextFactory jndiLdapContextFactory = ( JndiLdapContextFactory )ldapContextFactory; Dictionary <string, object> env = new Dictionary <string, object>(); env[Context.INITIAL_CONTEXT_FACTORY] = jndiLdapContextFactory.ContextFactoryClassName; env[Context.PROVIDER_URL] = jndiLdapContextFactory.Url; LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); StartTlsRequest startTlsRequest = new StartTlsRequest(); StartTlsResponse tls = ( StartTlsResponse )ctx.extendedOperation(startTlsRequest); tls.negotiate(); ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiLdapContextFactory.AuthenticationMechanism); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); // do a lookup of the user to trigger authentication ctx.lookup(principal.ToString()); return(ctx); } catch (IOException e) { LdapUtils.closeContext(ctx); _securityLog.error(WithRealm("Failed to negotiate TLS connection with '%s': ", Server(jndiLdapContextFactory), e)); throw new CommunicationException(e.Message); } catch (Exception t) { LdapUtils.closeContext(ctx); _securityLog.error(WithRealm("Unexpected failure to negotiate TLS connection with '%s': ", Server(jndiLdapContextFactory), t)); throw t; } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected org.apache.shiro.authc.AuthenticationInfo createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, javax.naming.ldap.LdapContext ldapContext) throws javax.naming.NamingException protected internal override AuthenticationInfo CreateAuthenticationInfo(AuthenticationToken token, object ldapPrincipal, object ldapCredentials, LdapContext ldapContext) { // If authorization is enabled but useSystemAccountForAuthorization is disabled, we should perform // the search for groups directly here while the user's authenticated ldap context is open. if (_authorizationEnabled && !_useSystemAccountForAuthorization) { string username = ( string )token.Principal; ISet <string> roleNames = FindRoleNamesForUser(username, ldapContext); CacheAuthorizationInfo(username, roleNames); } if (AuthenticationCachingEnabled) { SimpleHash hashedCredentials = _secureHasher.hash(( sbyte[] )token.Credentials); return(new ShiroAuthenticationInfo(token.Principal, hashedCredentials.Bytes, hashedCredentials.Salt, Name, AuthenticationResult.SUCCESS)); } else { return(new ShiroAuthenticationInfo(token.Principal, Name, AuthenticationResult.SUCCESS)); } }
public LdapRepository(LdapContext ldapContext) { _ldapContext = ldapContext; }
/// <summary> /// Invoked after the authentication before ClaimsIdentity is populated with claims retrieved through the LDAP connection. /// </summary> public virtual Task RetrieveLdapClaims(LdapContext context) => OnRetrieveLdapClaims(context);