/// <summary> /// /// </summary> /// <param name="ldapInfo"></param> /// <returns></returns> private static void ValidateConfigurations(LdapConfig ldapInfo) { if (ldapInfo == null) { throw new ApplicationException("Configurazioni LDAP non specificate"); } CheckProperty <string>(ldapInfo, "ServerName", true, 255); CheckProperty <string>(ldapInfo, "GroupDN", true, 255); CheckProperty <string>(ldapInfo, "DomainUserName", false, 255); CheckProperty <string>(ldapInfo, "DomainUserPassword", false, 255); if (ldapInfo.UserAttributes != null) { CheckProperty <string>(ldapInfo.UserAttributes, "UserID", true, 50); CheckProperty <string>(ldapInfo.UserAttributes, "Email", true, 255); CheckProperty <string>(ldapInfo.UserAttributes, "Matricola", true, 50); CheckProperty <string>(ldapInfo.UserAttributes, "Nome", true, 50); CheckProperty <string>(ldapInfo.UserAttributes, "Cognome", true, 50); CheckProperty <string>(ldapInfo.UserAttributes, "Sede", true, 255); } else { throw new ApplicationException("Nessun valore specificato per i campi LDAP"); } }
public async Task Setup() { // Build Connection to Vault. _vault = await VaultServerRef.ConnectVault("AppRoleVault"); //_vault = new VaultAgentAPI ("AppRoleVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true); _vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault); _ldapMountName = _uniqueKeys.GetKey("LDAP"); // Define the engine. _ldapAuthEngine = (LdapAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_LDAP, "ldap_test", _ldapMountName); // Now create the Mount point. AuthMethod authMethod = new AuthMethod(_ldapMountName, EnumAuthMethods.LDAP); authMethod.Description = "Ldap Test"; Assert.True(await _vaultSystemBackend.AuthEnable(authMethod), "A10: Expected the LDAP Backend to have been enabled."); // Now build the LDAP Backend. _origConfig = _ldapAuthEngine.GetLDAPConfigFromFile(@"C:\a_Dev\Configs\LDAP_Test.json"); SetLDAPConfig(_ldapMountName, _origConfig); // Save the Config. We do this here so the SetLDAPConfig can be used for multiple engines. Assert.True(await _ldapAuthEngine.ConfigureLDAPBackend(_origConfig), "A100: Expected the LDAP Configuration method to return True"); // Initialize the LDAP Login Connector. _ldapLoginConnector = new LDAPLoginConnector(_vault, _ldapAuthEngine.MountPoint, "Test LDAP Backend"); // Load the Test Data Object LoadTestData(); }
public static void AddVcpShLdap(this IServiceCollection services, IConfiguration config, Action <DbContextOptionsBuilder> dbContextOptionsBuilder) { var ldapConfig = new LdapConfig(); config.GetSection("ldap").Bind(ldapConfig); ldapConfig.AuthorizationConfigurationSection = config.GetSection("Authorization"); services.AddSingleton(ldapConfig); services.AddScoped <ILdapConnection, LdapConnection>(); // add change tracking context if (ldapConfig.LogChanges) { services.AddDbContext <ChangeTrackingDbContext>(dbContextOptionsBuilder); } else { services.AddSingleton(_ => (ChangeTrackingDbContext)null); } // add cache if (ldapConfig.UseCache) { services.AddSingleton <ILdapCache>(new LdapCache()); } else { services.AddSingleton(_ => (ILdapCache)null); } }
public UserService(IOptions <Token> appSettings, IOptions <LdapConfig> config, IUserModelRepository data, ILogger <UserService> logger) { _appSettings = appSettings.Value; _config = config.Value; _UserModelRepository = data; _logger = logger; }
/// <summary> /// Factory method servizi LDAP per una determinata amministrazione /// </summary> /// <param name="idAmministrazione"></param> /// <returns></returns> public static BaseLdapUserServices GetConfiguredInstance(string idAmministrazione) { // Reperimento configurazioni LDAP per l'amministrazione richiesta LdapConfig config = LdapConfigurations.GetLdapConfig(idAmministrazione); return(CreateInstance(config)); }
/// <summary> /// Configures the LDAP Backend for a new vault. /// </summary> /// <returns></returns> public async Task SetupLDAP() { // Create Config object - load defaults from file. LdapConfig ldapConfig = _ldapAuthEngine.GetLDAPConfigFromFile(@"C:\a_dev\Configs\AD_Cin_Connector.json"); try { if (!(await _vaultSystemBackend.AuthEnable(_authMethod))) { Console.WriteLine("Error: unable to create the backend"); return; } Console.WriteLine("LDAP Backend Mount created."); if (!await _ldapAuthEngine.ConfigureLDAPBackend(ldapConfig)) { Console.WriteLine("Error setting the LDAP Configuration"); return; } Console.WriteLine("LDAP Config saved"); } catch (VaultException e) { if (e.SpecificErrorCode != EnumVaultExceptionCodes.BackendMountAlreadyExists) { Console.WriteLine("Error connecting to authentication backend - {0}", e.Message); } } bool exists = await _vaultSystemBackend.AuthExists(LDAP_MOUNTNAME); }
/// <summary> /// Reperimento degli utenti in LDAP appartenenti al gruppo configurato in amministrazione /// </summary> /// <param name="ldapInfo"></param> /// <returns></returns> private static Dictionary <string, LdapUser> GetLdapUsers(LdapConfig ldapInfo) { Dictionary <string, LdapUser> result = new Dictionary <string, LdapUser>(); LdapUser userError = null; try { // Creazione dei servizi per la gestione LDAP BaseLdapUserServices ldapUserServices = LdapUserServicesFactory.CreateInstance(ldapInfo); // Reperimento da LDAP di tutti gli utenti appartenti al gruppo configurato foreach (LdapUser user in ldapUserServices.GetUsers()) { userError = user; logger.Debug("GET UTENTE LDAP utente userid " + user.UserID + " matricola " + user.Matricola + " DN " + user.DN + " email " + user.Email); try { result.Add(user.Key.ToUpper(), user); } catch (Exception ex) { } } } catch (Exception ex) { logger.Debug("errore per utente userid " + userError.UserID + " matricola " + userError.Matricola + " " + ex.StackTrace + " " + ex.Message); } return(result); }
public LdapAuthenticationService(IOptions <LdapConfig> config) { _config = config.Value; _connection = new LdapConnection { SecureSocketLayer = true }; }
public UserAuthentication(IOptions <LdapConfig> config, ILogger <UserAuthentication> logger, IUsuarioRepositorio repoUsuario, IPerfilRepositorio repoPerfil, IHttpContextAccessor httpContextAccessor) { _logger = logger; this.config = config.Value; this.repoUsuario = repoUsuario; this.repoPerfil = repoPerfil; _httpContextAccessor = httpContextAccessor; }
public void UserDN_No_DNsuffix_SetCorrectly() { string user = "******"; LdapConfig lc = new LdapConfig(); lc.UserDN = user; Assert.AreEqual(user, lc.UserDN, "A10: Unexpected userDN"); }
public void BindDN_No_DNsuffix_SetCorrectly() { string bind = "tstUSEROU,DC=practice,DC=org"; LdapConfig lc = new LdapConfig(); lc.BindDN = bind; Assert.AreEqual(bind, lc.BindDN, "A10: Unexpected bindDN"); }
/// <summary> /// Sets the configuration for the given LDAP Backend. The configuration is everything need to setup an LDAP connection. /// </summary> /// <param name="ldapConfig">The LdapConfig object that contains all the LDAP connection information.</param> /// <returns></returns> public async Task <bool> ConfigureLDAPBackend(LdapConfig ldapConfig) { string path = MountPointPath + "config"; string json = JsonConvert.SerializeObject(ldapConfig); VaultDataResponseObjectB vdro = await ParentVault._httpConnector.PostAsync_B(path, "LdapAuthEngine: ConfigureLDAPBackend", json, false); return(vdro.Success); }
public void GroupDN_No_DNsuffix_SetCorrectly() { string group = "tstUSEROU,DC=practice,DC=org"; LdapConfig lc = new LdapConfig(); lc.GroupDN = group; Assert.AreEqual(group, lc.GroupDN, "A10: Unexpected groupDN"); }
public void BindDN_DNsuffixSpecified_SetCorrectly() { string dnSuffix = "dc=test,dc=tst,dc=org"; string bind = "tstUSEROU"; LdapConfig lc = new LdapConfig(dnSuffix); lc.BindDN = bind; Assert.AreEqual(bind + "," + dnSuffix, lc.BindDN, "A10: Unexpected bindDN"); }
public void UserDN_DNsuffixSpecified_SetCorrectly() { string dnSuffix = "dc=test,dc=tst,dc=org"; string user = "******"; LdapConfig lc = new LdapConfig(dnSuffix); lc.UserDN = user; Assert.AreEqual(user + "," + dnSuffix, lc.UserDN, "A10: Unexpected userDN"); }
public LdapAuthService(IOptions <LdapConfig> config, IStudentService studentService, ITeacherService teacherService) { _studentService = studentService; _teacherService = teacherService; _config = config.Value; _connection = new LdapConnection() { SecureSocketLayer = false }; }
/// <summary> /// /// </summary> /// <param name="ldapInfo"></param> /// <returns></returns> private static void ValidateConfigurations(LdapConfig ldapInfo) { if (ldapInfo == null) { throw new ApplicationException("Configurazioni LDAP non specificate"); } CheckProperty <string>(ldapInfo, "ServerName", true, 255); CheckProperty <string>(ldapInfo, "GroupDN", true, 255); }
public LdapService(IOptions <LdapConfig> cfg, IHttpContextAccessor httpCtxAccessor, ILogger <LdapService> logger) { httpContextAccessor = httpCtxAccessor; config = cfg.Value; this.logger = logger; connection = new LdapConnection { SecureSocketLayer = false }; }
public void GroupDN_DNsuffixSpecified_SetCorrectly() { string dnSuffix = "dc=test,dc=tst,dc=org"; string group = "tstUSEROU"; LdapConfig lc = new LdapConfig(dnSuffix); lc.GroupDN = group; Assert.AreEqual(group + "," + dnSuffix, lc.GroupDN, "A10: Unexpected groupDN"); }
public LdapAuthenticationService(DBBakumContext db, IOptions <LdapConfig> config, RoleManager <IdentityRole> roleManager, UserManager <UserProfile> userManager) : base(db) { _config = config.Value; _connection = new LdapConnection { SecureSocketLayer = false }; this._roleManager = roleManager; this._userManager = userManager; }
//--- Methods --- public override Yield Start(XDoc config, Result result) { yield return(Coroutine.Invoke(base.Start, config, new Result()).Catch(result)); // TODO MaxM: Validate config. _config = new LdapConfig(); _config.LdapHostname = config["hostname"].AsText ?? config["ldaphostname"].AsText; _config.LdapSearchBase = config["searchbase"].AsText ?? config["ldapsearchbase"].AsText; _config.BindingDn = config["bindingdn"].AsText ?? config["ldapbindingdn"].AsText; _config.BindingPw = config["bindingpw"].AsText ?? config["ldapbindingpw"].AsText; _config.UserQuery = config["userquery"].AsText ?? config["ldapuserquery"].AsText; _config.DisplayNamePattern = config["displayname-pattern"].AsText; _config.GroupQuery = config["groupquery"].AsText ?? "(&(objectClass=group)(cn=$1))"; _config.GroupQueryAll = config["groupqueryall"].AsText ?? "(objectClass=group)"; _config.GroupMembersAttribute = config["groupmembersattribute"].AsText ?? "memberof"; _config.GroupMembershipQuery = config["groupmembershipquery"].AsText; _config.UserNameAttribute = config["usernameattribute"].AsText; _config.GroupNameAttribute = config["groupnameattribute"].AsText; _config.SSL = config["ssl"].AsBool ?? false; _config.SSLIgnoreCertErrors = config["ssl-ignore-cert-errors"].AsBool ?? false; _config.LdapTimeOut = Math.Max(MIN_TIMEOUT, config["timeout"].AsInt ?? config["ldaptimeout"].AsInt ?? DEFAULT_TIMEOUT); _config.VerboseLogging = config["verboselogging"].AsBool ?? false; try { string ARGERROR = "LDAP Service config parameter not provided"; // validate configuration if (string.IsNullOrEmpty(_config.LdapHostname)) { throw new ArgumentException(ARGERROR, "hostname"); } if (string.IsNullOrEmpty(_config.LdapSearchBase)) { throw new ArgumentException(ARGERROR, "searchbase"); } if (string.IsNullOrEmpty(_config.BindingDn)) { throw new ArgumentException(ARGERROR, "bindingdn"); } if (string.IsNullOrEmpty(_config.UserQuery)) { throw new ArgumentException(ARGERROR, "userquery"); } } catch (ArgumentException ae) { throw new DreamBadRequestException(ae.Message); } result.Return(); }
/// <summary> /// Returns an LDAPConfig object that was initialized from values in a config file. /// </summary> /// <param name="filename">The file that contains the LDAP configuration you wish to load</param> /// <returns></returns> public LdapConfig GetLDAPConfigFromFile(string filename) { // Read a JSON Config file containing LDAP Credentials from a JSON file into the class. JsonSerializer jsonSerializer = new JsonSerializer(); string json = File.ReadAllText(filename); // Append JSON to existing objects values. LdapConfig ldapConfig = new LdapConfig(); jsonSerializer.Populate(new StringReader(json), ldapConfig); return(ldapConfig); }
/// <summary> /// Factory method /// </summary> /// <param name="info"></param> /// <returns></returns> public static BaseLdapUserServices CreateInstance(LdapConfig info) { if (info.SSL) { // Creazione istanza per l'accesso ad LDAP tramite SSL return(new LdapUserServicesSSL(info)); } else { return(new LdapUserServices(info)); } }
/// <summary> /// Base Validation of Config file loaded from JSON /// </summary> /// <param name="ldapConfig"></param> /// <param name="withDNSSuffix"></param> /// <param name="withAD"></param> /// <returns></returns> private bool ValidateConfigFromJSON(LdapConfig ldapConfig, bool withDNSSuffix = false, bool withAD = false) { // TODO all tests are backwards, actual, expected. fix Assert.AreEqual(ldapConfig.BindPassword, "password"); Assert.IsFalse(ldapConfig.CaseSensitiveNames); Assert.AreEqual(ldapConfig.Certificate, ""); Assert.IsTrue(ldapConfig.DenyNullBind); Assert.IsFalse(ldapConfig.DiscoverDN); Assert.IsTrue(ldapConfig.InsecureTLS); Assert.AreEqual(ldapConfig.LDAPServers, "ldaps://testserver:686"); Assert.IsFalse(ldapConfig.StartTLS); Assert.AreEqual(ldapConfig.TLSMaxVersion, "tls12"); Assert.AreEqual(ldapConfig.TLSMinVersion, "tls12"); if (withDNSSuffix) { Assert.AreEqual(ldapConfig.DN_Suffix, "DC=test,dc=org"); Assert.AreEqual(ldapConfig.BindDN, FullDNValue("CN=SearchUser", ldapConfig.DN_Suffix)); Assert.AreEqual(ldapConfig.GroupDN, FullDNValue("OU=Groups", ldapConfig.DN_Suffix)); } else { Assert.AreEqual(ldapConfig.BindDN, ""); Assert.AreEqual(ldapConfig.BindPassword, ""); Assert.AreEqual(ldapConfig.GroupDN, ""); Assert.AreEqual(ldapConfig.DN_Suffix, ""); } if (withAD) { Assert.IsTrue(ldapConfig.IsActiveDirectoryConnection); Assert.AreEqual("cn", ldapConfig.GroupAttr); Assert.AreEqual("samaccountname", ldapConfig.UserAttr); Assert.AreEqual("(\u0026(objectClass=group)(member:1.2.840.113556.1.4.1941:={{.UserDN}}))", ldapConfig.GroupFilter); } else { Assert.IsFalse(ldapConfig.IsActiveDirectoryConnection); Assert.AreEqual("", ldapConfig.GroupAttr); Assert.AreEqual("", ldapConfig.UserAttr); Assert.AreEqual("", ldapConfig.GroupFilter); } return(true); }
/// <summary> /// constructor de la clase donde se configuran la conexión del ldap /// y se lee la configuración del ldap /// </summary> /// <param name="config"></param> public LdapAuthenticationService(IOptions <LdapConfig> config) { /// <summary> /// Se lee la configuración del ldap del json y se añade por inyección de dependencia /// </summary> _config = config.Value; /// <summary> /// se inicializa el servicio del que manipula el ldap /// </summary> _connection = new LdapConnection { SecureSocketLayer = false }; }
public void SetADDefaults_Works() { LdapConfig a = new LdapConfig(); a.SetActiveDirectoryDefaults(); // Store off some of the values: string exGroupFilter = a.GroupFilter; string exGroupAttr = a.GroupAttr; string exUserAttr = a.UserAttr; // Validate the AD fields are set. Assert.IsNotEmpty(exGroupAttr, "A10: Expected the GroupAttr property to be set."); Assert.IsNotEmpty(exGroupFilter, "A20: Expected the GroupFilter property to be set."); Assert.IsNotEmpty(exUserAttr, "A30: Expected the UserAttr property to be set."); }
public void ConnectionManagerTest() { string[] servers = new string[] { "teste:389", "teste2:389" }; var lconfig = new LdapConfig(servers, false, 1000, 2, "testeDN", "testCred", "testSearch", "testFilter", "testAdmin"); Assert.NotNull(lconfig.adminCn); Assert.Equal(2, lconfig.servers.Length); var lcm = LdapConnectionManager.Instance; Exception ex = Assert.Throws <NullException>(() => lcm.GetConnection(null)); Exception ex2 = Assert.ThrowsAny <Exception>(() => lcm.GetConnection(lconfig)); }
public async Task <ActionResult <dynamic> > Autheticate([FromBody] LdapConfig model) { var user = _authService.Login(model.Username, model.Password); var claimsIdentity = new ClaimsIdentity(userClaims, _authService.GetType().Name); if (Array.Exists(user.Roles, s => s.Contains("aspnetcore.ldap"))) { claimsIdentity.AddClaim(new Claim("aspnetcore.ldap.user", "true")); } return(new { user = user, token = token }); }
/// <summary> /// Memorizzazione configurazioni per la connessione ad un archivio LDAP /// </summary> /// <param name="idAmministrazione"></param> /// <param name="ldapInfo"></param> public static void SaveLdapConfig(string idAmministrazione, LdapConfig ldapInfo) { using (DocsPaDB.TransactionContext transactionalContext = new DocsPaDB.TransactionContext()) { // Verifica se l'integrazione con ldap è attivata CheckForLdapIntegrationActivated(); // Validazione dati di configurazione ValidateConfigurations(ldapInfo); DocsPaDB.Query_DocsPAWS.Ldap ldapDbServices = new DocsPaDB.Query_DocsPAWS.Ldap(); ldapDbServices.SaveLdapConfig(idAmministrazione, ldapInfo); transactionalContext.Complete(); } }
/// <summary> /// Reperimento delle informazioni per l'integrazione con ldap per una singola amministrazione /// </summary> /// <param name="idAmministrazione"></param> /// <returns></returns> public DocsPaVO.Ldap.LdapConfig GetLdapConfig(string idAmministrazione) { try { DocsPaVO.Ldap.LdapConfig info = null; using (DocsPaDB.DBProvider dbProvider = new DBProvider()) { DocsPaUtils.Query queryDef = DocsPaUtils.InitQuery.getInstance().getQuery("S_GET_LDAP_CONFIG"); queryDef.setParam("idAmm", idAmministrazione); string commandText = queryDef.getSQL(); logger.Debug(commandText); using (IDataReader reader = dbProvider.ExecuteReader(commandText)) { if (reader.Read()) { info = new LdapConfig(); info.ServerName = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "SERVER_NAME", false); info.DomainUserName = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "USER_NAME", true, string.Empty); info.GroupDN = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "GROUP_DN", false); info.UserAttributes = new LdapUserAttributes(); info.UserAttributes.UserId = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "USERID_ATTRIBUTE", true, string.Empty); info.UserAttributes.Email = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "EMAIL_ATTRIBUTE", true, string.Empty); info.UserAttributes.Matricola = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "MATRICOLA_ATTRIBUTE", true, info.UserAttributes.UserId); info.UserAttributes.Nome = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "NOME_ATTRIBUTE", true, string.Empty); info.UserAttributes.Cognome = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "COGNOME_ATTRIBUTE", true, string.Empty); info.UserAttributes.Sede = DocsPaUtils.Data.DataReaderHelper.GetValue <string>(reader, "SEDE_ATTRIBUTE", true, string.Empty); } } } return(info); } catch (Exception ex) { string errorMessage = "Errore nel reperimento delle configurazione LDAP per l'amministrazione"; logger.Debug(errorMessage, ex); throw new ApplicationException(errorMessage, ex); } }
//--- Methods --- protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); // TODO MaxM: Validate config. _config = new LdapConfig(); _config.LdapHostname = config["hostname"].AsText ?? config["ldaphostname"].AsText; _config.LdapSearchBase = config["searchbase"].AsText ?? config["ldapsearchbase"].AsText; _config.BindingDn = config["bindingdn"].AsText ?? config["ldapbindingdn"].AsText; _config.BindingPw = config["bindingpw"].AsText ?? config["ldapbindingpw"].AsText; _config.UserQuery = config["userquery"].AsText ?? config["ldapuserquery"].AsText; _config.DisplayNamePattern = config["displayname-pattern"].AsText; _config.GroupQuery = config["groupquery"].AsText ?? "(&(objectClass=group)(cn=$1))"; _config.GroupQueryAll = config["groupqueryall"].AsText ?? "(objectClass=group)"; _config.GroupMembersAttribute = config["groupmembersattribute"].AsText ?? "memberof"; _config.GroupMembershipQuery = config["groupmembershipquery"].AsText; _config.UserNameAttribute = config["usernameattribute"].AsText; _config.GroupNameAttribute = config["groupnameattribute"].AsText; _config.SSL = config["ssl"].AsBool ?? false; _config.SSLIgnoreCertErrors = config["ssl-ignore-cert-errors"].AsBool ?? false; _config.LdapTimeOut = Math.Max(MIN_TIMEOUT, config["timeout"].AsInt ?? config["ldaptimeout"].AsInt ?? DEFAULT_TIMEOUT); _config.VerboseLogging = config["verboselogging"].AsBool ?? false; try { string ARGERROR = "LDAP Service config parameter not provided"; // validate configuration if (string.IsNullOrEmpty(_config.LdapHostname)) { throw new ArgumentException(ARGERROR, "hostname"); } if (string.IsNullOrEmpty(_config.LdapSearchBase)) { throw new ArgumentException(ARGERROR, "searchbase"); } if (string.IsNullOrEmpty(_config.BindingDn)) { throw new ArgumentException(ARGERROR, "bindingdn"); } if (string.IsNullOrEmpty(_config.UserQuery)) { throw new ArgumentException(ARGERROR, "userquery"); } } catch (ArgumentException ae) { throw new DreamBadRequestException(ae.Message); } result.Return(); }