// public methods /// <summary> /// Authenticates the connection against the given database. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> public void Authenticate(MongoConnection connection, MongoCredential credential) { string nonce; try { var nonceCommand = new CommandDocument("getnonce", 1); var nonceResult = RunCommand(connection, credential.Source, nonceCommand); nonce = nonceResult.Response["nonce"].AsString; } catch (MongoCommandException ex) { throw new MongoAuthenticationException("Error getting nonce for authentication.", ex); } try { var passwordDigest = ((PasswordEvidence)credential.Evidence).ComputeMongoCRPasswordDigest(credential.Username); var digest = MongoUtils.Hash(nonce + credential.Username + passwordDigest); var authenticateCommand = new CommandDocument { { "authenticate", 1 }, { "user", credential.Username }, { "nonce", nonce }, { "key", digest } }; RunCommand(connection, credential.Source, authenticateCommand); } catch (MongoCommandException ex) { var message = string.Format("Invalid credential for database '{0}'.", credential.Source); throw new MongoAuthenticationException(message, ex); } }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(Internal.MongoConnection connection, MongoCredential credential) { return new ManagedDigestMD5Implementation( connection.ServerInstance.Address.Host, credential.Username, ((PasswordEvidence)credential.Evidence).Password); }
// public methods /// <summary> /// Authenticates the connection against the given database. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> public void Authenticate(MongoConnection connection, MongoCredential credential) { var nonceCommand = new CommandDocument("getnonce", 1); var commandResult = connection.RunCommand(credential.Source, QueryFlags.None, nonceCommand, false); if (!commandResult.Ok) { throw new MongoAuthenticationException( "Error getting nonce for authentication.", new MongoCommandException(commandResult)); } var nonce = commandResult.Response["nonce"].AsString; var passwordDigest = MongoUtils.Hash(credential.Username + ":mongo:" + ((PasswordEvidence)credential.Evidence).Password); var digest = MongoUtils.Hash(nonce + credential.Username + passwordDigest); var authenticateCommand = new CommandDocument { { "authenticate", 1 }, { "user", credential.Username }, { "nonce", nonce }, { "key", digest } }; commandResult = connection.RunCommand(credential.Source, QueryFlags.None, authenticateCommand, false); if (!commandResult.Ok) { var message = string.Format("Invalid credential for database '{0}'.", credential.Source); throw new MongoAuthenticationException( message, new MongoCommandException(commandResult)); } }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { var serviceName = credential.GetMechanismProperty<string>("SERVICE_NAME", "mongodb"); var canonicalizeHostname = credential.GetMechanismProperty<bool>("CANONICALIZE_HOST_NAME", false); var hostname = connection.ServerInstance.Address.Host; if (canonicalizeHostname) { var entry = Dns.GetHostEntry(hostname); if (entry != null) { hostname = entry.HostName; } } // TODO: provide an override to force the use of gsasl? if (__useGsasl) { return new GsaslGssapiImplementation( serviceName, hostname, credential.Username, credential.Evidence); } return new WindowsGssapiImplementation( serviceName, hostname, credential.Username, credential.Evidence); }
public static MongoClientSettings GetMongoClientSettings(string host, int port, MongoCredential credentials) { return new MongoClientSettings { Server = new MongoServerAddress(host, port), Credentials = new[] { credentials } }; }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns> /// The initial step. /// </returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { var securePassword = ((PasswordEvidence)credential.Evidence).SecurePassword; var dataString = string.Format("\0{0}\0{1}", credential.Username, MongoUtils.ToInsecureString(securePassword)); var bytes = new UTF8Encoding(false, true).GetBytes(dataString); return new SaslCompletionStep(bytes); }
// public methods /// <summary> /// Determines whether this instance can authenticate with the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can authenticate with the specified credential; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public bool CanUse(MongoCredential credential) { if (!credential.Mechanism.Equals("GSSAPI", StringComparison.InvariantCultureIgnoreCase) || !(credential.Identity is MongoExternalIdentity)) { return false; } if (__useGsasl) { // GSASL relies on kinit to work properly and hence, the evidence is external. return credential.Evidence is ExternalEvidence; } return true; }
// private methods private void Authenticate(MongoCredential credential, List<string> serverSupportedMethods) { foreach (var clientSupportedMethod in __clientSupportedMethods) { if (serverSupportedMethods.Contains(clientSupportedMethod.Name) && clientSupportedMethod.CanUse(credential)) { clientSupportedMethod.Authenticate(_connection, credential); return; } } var message = string.Format("Unable to negotiate a protocol to authenticate. Credential for source {0}, username {1} over protocol {2} could not be authenticated", credential.Source, credential.Username, credential.AuthenticationProtocol); throw new MongoSecurityException(message); }
// private methods private void Authenticate(MongoCredential credential) { foreach (var clientSupportedProtocol in __clientSupportedProtocols) { if (clientSupportedProtocol.CanUse(credential)) { clientSupportedProtocol.Authenticate(_connection, credential); return; } } var message = string.Format("Unable to find a protocol to authenticate. The credential for source {0}, username {1} over mechanism {2} could not be authenticated.", credential.Source, credential.Username, credential.Mechanism); throw new MongoSecurityException(message); }
// public methods /// <summary> /// Authenticates the connection against the given database. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> public void Authenticate(MongoConnection connection, MongoCredential credential) { using (var conversation = new SaslConversation()) { var currentStep = _mechanism.Initialize(connection, credential); var command = new CommandDocument { { "saslStart", 1 }, { "mechanism", _mechanism.Name }, { "payload", currentStep.BytesToSendToServer } }; while (true) { CommandResult result; try { result = RunCommand(connection, credential.Source, command); } catch (MongoCommandException ex) { var message = "Unknown error occured during authentication."; var code = ex.CommandResult.Code; var errmsg = ex.CommandResult.ErrorMessage; if(code.HasValue && errmsg != null) { message = string.Format("Error: {0} - {1}", code, errmsg); } throw new MongoSecurityException(message, ex); } if (result.Response["done"].AsBoolean) { break; } currentStep = currentStep.Transition(conversation, result.Response["payload"].AsByteArray); command = new CommandDocument { { "saslContinue", 1 }, { "conversationId", result.Response["conversationId"].AsInt32 }, { "payload", currentStep.BytesToSendToServer } }; } } }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { // TODO: provide an override to force the use of gsasl? if (__useGsasl) { return new GsaslGssapiImplementation( connection.ServerInstance.Address.Host, credential.Username, credential.Evidence); } return new WindowsGssapiImplementation( connection.ServerInstance.Address.Host, credential.Username, credential.Evidence); }
public void Authentication_succeeds_when_user_has_both_scram_sha_mechanisms_and_mechanism_is_Scram_Sha_256( [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.ScramSha256Authentication).Authentication(true); var client = DriverTestConfiguration.Client; var userName = $"both{Guid.NewGuid()}"; var password = "******"; CreateAdminDatabaseReadWriteUser(client, userName, password, "SCRAM-SHA-256", "SCRAM-SHA-1"); var settings = client.Settings.Clone(); settings.Credential = MongoCredential .FromComponents(mechanism: "SCRAM-SHA-256", source: null, username: userName, password: password); AssertAuthenticationSucceeds(settings, async); }
// public methods /// <summary> /// Authenticates the specified connection with the given credential. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> public void Authenticate(MongoConnection connection, MongoCredential credential) { try { var command = new CommandDocument { { "authenticate", 1 }, { "mechanism", Name }, { "user", credential.Username } }; RunCommand(connection, credential.Source, command); } catch (MongoCommandException ex) { throw new MongoAuthenticationException(string.Format("Unable to authenticate '{0}' using '{1}'.", credential.Username, Name), ex); } }
private MongoClientSettings MontarConexaoComLog() { var configuracoes = new MongoClientSettings { Server = new MongoServerAddress(ConfiguracaoDb.Host, ConfiguracaoDb.Porta), Credential = MongoCredential.CreateCredential( ConfiguracaoDb.Banco, ConfiguracaoDb.Usuario, ConfiguracaoDb.Senha), ClusterConfigurator = cb => cb.Subscribe <CommandStartedEvent>(x => _suporteLog.LogarEvento(x)) }; return(configuracoes); }
private bool InitConnector(string dbServer, string dbName, string username, string password, SslProtocols protocols = SslProtocols.None) { MongoClientSettings settings; if (dbServer.Contains("mongodb://")) { settings = MongoClientSettings.FromUrl(new MongoUrl(dbServer)); } else { settings = new MongoClientSettings() { Server = new MongoServerAddress(dbServer) }; if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { var credential = MongoCredential.CreateCredential(dbName, username, password); settings.Credentials = new List <MongoCredential>() { credential }; } } if (protocols != SslProtocols.None) { settings.SslSettings = new SslSettings() { EnabledSslProtocols = protocols }; } var client = new MongoClient(settings); try { Db = client.GetDatabase(dbName); Db.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(); return(true); } catch (Exception ex) { HasError = $"Connection error: {ex.Message}"; return(false); } }
private IMongoDatabase GetMongoDatabase() { string host = EnvironmentUtils.GetEnvironmentVariable("MONGODB_HOST", "localhost"); string port = EnvironmentUtils.GetEnvironmentVariable("MONGODB_PORT", "27017"); string database = EnvironmentUtils.GetEnvironmentVariable("MONGODB_DATABASE", "default"); string username = EnvironmentUtils.GetEnvironmentVariable("MONGODB_AUTHENTICATION_USERNAME", "mongo"); string password = EnvironmentUtils.GetEnvironmentVariable("MONGODB_AUTHENTICATION_PASSWORD", "mongo"); string authenticationDatabase = EnvironmentUtils.GetEnvironmentVariable("MONGODB_AUTHENTICATION_DATABASE", "admin"); var settings = new MongoClientSettings { Server = new MongoServerAddress(host, int.Parse(port)), Credential = MongoCredential.CreateCredential(authenticationDatabase, username, password) }; var mongoClient = new MongoClient(settings); return(mongoClient.GetDatabase(database)); }
/// <summary> Mongo服务器 </summary> /// <returns></returns> private IMongoClient Client() { var settings = new MongoClientSettings { Servers = _config.Servers.Select(t => new MongoServerAddress(t.Host, t.Port)), SocketTimeout = TimeSpan.FromSeconds(_config.Timeout), ConnectTimeout = TimeSpan.FromSeconds(_config.Timeout) }; var cred = _config.Credentials.FirstOrDefault(t => t.Database == _database); if (cred != null) { settings.Credential = MongoCredential.CreateCredential(cred.Database, cred.User, cred.Pwd); } var client = new MongoClient(settings); return(client); }
public void TestBadPassword() { RequireEnvironment.Check().EnvironmentVariable("EXPLICIT"); var currentCredential = _settings.Credential; _settings.Credential = MongoCredential.CreatePlainCredential(currentCredential.Source, currentCredential.Username, "wrongPassword"); var client = new MongoClient(_settings); Assert.Throws <TimeoutException>(() => { client .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName) .GetCollection <BsonDocument>(__collectionName) .FindSync(new BsonDocument()) .ToList(); }); }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { // TODO: provide an override to force the use of gsasl? bool useGsasl = !Environment.OSVersion.Platform.ToString().Contains("Win"); if (useGsasl) { throw new NotImplementedException("Gssapi Support on Non-Windows Machinse is Not Implemented."); //return new GsaslGssapiImplementation( // connection.ServerInstance.Address.Host, // credential.Username, // credential.Evidence); } return new WindowsGssapiImplementation( connection.ServerInstance.Address.Host, credential.Username, credential.Evidence); }
public MongoContext() { string mongoDb = Program.MONGO_DB; string mongoUsername = Program.MONGO_USERNAME; string mongoPassword = Program.MONGO_PASSWORD; // I don't care anymore, just make it work or something. int mongoPort = int.Parse(Program.MONGO_PORT); string mongoHost = Program.MONGO_HOST; Console.WriteLine(mongoHost); var credential = MongoCredential.CreateCredential(mongoDb, mongoUsername, mongoPassword); _client = new MongoClient($"mongodb://{mongoUsername}:{mongoPassword}@{mongoHost}"); //new MongoClient(settings); Database = _client.GetDatabase(mongoDb); Console.WriteLine("Pinging mongodb"); Database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(); Console.WriteLine("Done mongodb"); }
public void Authentication_fails_when_user_has_Scram_Sha_1_mechanism_and_mechanism_is_Scram_Sha_256( [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.ScramSha256Authentication).Authentication(true); // mechanisms field in createUser command requires server >=4.0 var client = DriverTestConfiguration.Client; var userName = $"sha1{Guid.NewGuid()}"; var password = "******"; CreateAdminDatabaseReadWriteUser(client, userName, password, "SCRAM-SHA-1"); var settings = client.Settings.Clone(); settings.Credential = MongoCredential .FromComponents(mechanism: "SCRAM-SHA-256", source: null, username: userName, password: password); settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); AssertAuthenticationFails(settings, async); }
public SpotCharterQueryRepository(string host = "localhost", string database = "spotService", int port = 27017, string username = null, string password = null) { this.username = username; this.password = password; this.database = database; this.credential = MongoCredential.CreateCredential(this.database, this.username, this.password); this.clientSettings = new MongoClientSettings() { Server = new MongoServerAddress(host, port), GuidRepresentation = GuidRepresentation.CSharpLegacy, Credentials = new List <MongoCredential>() { credential }, }; }
public void Authentication_succeeds_when_user_has_Scram_Sha_1_Mechanism_and_mechanism_is_not_specified( [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.ScramSha256Authentication).Authentication(true); // mechanisms field in createUser command requires server >=4.0 var client = DriverTestConfiguration.Client; var userName = $"sha1{Guid.NewGuid()}"; var password = "******"; CreateAdminDatabaseReadWriteUser(client, userName, password, "SCRAM-SHA-1"); var settings = client.Settings.Clone(); settings.Credential = MongoCredential .FromComponents(mechanism: null, source: null, username: userName, password: password); AssertAuthenticationSucceeds(settings, async, speculativeAuthenticatationShouldSucceedIfPossible: false); }
// http://blog.denouter.net/2013/07/c-mongodb-driver-mongocredentials.html public void CredentialTest() { // As of version 1.8 of the official mongoDB c# driver the MongoCredentials-class is gone ... // var client = new MongoClient("mongodb://192.168.1.2"); // var server = client.GetServer(); // var db = server.GetDatabase("myDatabase", new MongoCredentials("myUser", "myPassword")); MongoClientSettings cls = new MongoClientSettings() { Credentials = new MongoCredential[] { MongoCredential.CreateMongoCRCredential("myDatabase", "myUser", "myPassword") }, Server = new MongoServerAddress("192.168.1.2") }; MongoClient client = new MongoClient(cls); MongoServer server = client.GetServer(); MongoDatabase db = server.GetDatabase("myDatabase"); } // End Sub CredentialTest
public MongoPersistence(string host, int port, string database, string username, SecureString password) { var clientSettings = new MongoClientSettings { Server = new MongoServerAddress(host, port) }; if (username != null && password != null) { clientSettings.Credentials = new[] { MongoCredential.CreateCredential(database, username, password) }; } password?.Dispose(); _client = new MongoClient(clientSettings); _database = _client.GetDatabase(database); _collectionLookup = new Dictionary <Type, string>(); _usedCollectionNames = new HashSet <string>(); Init(); }
public MongoBank(Action <ApiLogMessage> logger, string userCollectionName = "users", string transactionsCollectionName = "transactions", string fieldName = "money") : base(logger) { Client = new MongoClient(new MongoClientSettings { ApplicationName = Listener.Config.MongoSettings.ApplicationName, Server = new MongoServerAddress(Listener.Config.MongoSettings.Host, (int)Listener.Config.MongoSettings.Port), Credential = Listener.Config.MongoSettings.Database == null || Listener.Config.MongoSettings.Username == null || Listener.Config.MongoSettings.Password == null ? null : MongoCredential.CreateCredential(Listener.Config.MongoSettings.Database, Listener.Config.MongoSettings.Username, Listener.Config.MongoSettings.Password), UseSsl = true }); Db = Client.GetDatabase(Listener.Config.MongoSettings.Database); UserCollectionName = userCollectionName; TransactionsCollectionName = transactionsCollectionName; FieldName = fieldName; }
public static void ConnectWithAuthentication() { string dbName = "ecommlight"; string userName = "******"; string password = "******"; var credentials = MongoCredential.CreateCredential(dbName, userName, password); MongoClientSettings clientSettings = new MongoClientSettings() { Credentials = new[] { credentials }, Server = new MongoServerAddress(hostName, 27017) }; MongoClient client = new MongoClient(clientSettings); Console.WriteLine("Connected as {0}", userName); }
public MongoDbContext() { MongoUrl mongoUrl = new MongoUrl(connectionString); MongoClientSettings mongoClientSettings = new MongoClientSettings(); mongoClientSettings.Server = mongoUrl.Server; if (mongoUrl.DatabaseName != null && mongoUrl.Username != null && mongoUrl.Password != null) { mongoClientSettings.Credential = MongoCredential.CreateCredential(mongoUrl.DatabaseName, mongoUrl.Username, mongoUrl.Password); } // mongoClientSettings.UseSsl = mongoUrl.UseSsl; // mongoClientSettings.VerifySslCertificate = false; MongoClient mongoClient = new MongoClient(mongoClientSettings); database = mongoClient.GetDatabase(mongoUrl.DatabaseName); }
/// <summary> /// MongoDbContext /// </summary> /// <param name="option"></param> public MongoDbContext(IOptions <MongoDbOptions> option) { //芒果数据库客户端配置 var settings = new MongoClientSettings { Server = MongoServerAddress.Parse(option.Value.ConnectionString) }; //开启授权操作 if (option.Value.IsEnabledAuthorization) { settings.Credential = MongoCredential.CreateCredential(option.Value.DataBase, option.Value.UserName, option.Value.Password); } var client = new MongoClient(settings); _db = client.GetDatabase(option.Value.DataBase); }
public TaskService(IServiceConfigurations _svcConfig, IAssignmentService assignSvc) { this.assignSvc = assignSvc; svcConfig = _svcConfig; var cred = MongoCredential.CreateCredential(svcConfig.DatabaseName, svcConfig.DbUser, svcConfig.DbPassword); var sett = new MongoClientSettings { Server = new MongoServerAddress(svcConfig.ServerAddress, svcConfig.Port), Credentials = new List <MongoCredential> { cred } }; MongoClient client = new MongoClient(sett); IMongoDatabase database = client.GetDatabase(svcConfig.DatabaseName); taskCollection = database.GetCollection <TaskModel>(svcConfig.TaskCollection); statusCollection = database.GetCollection <StatusModel>(svcConfig.StatusCollection); }
private IMongoDatabase CreateDatabaseConnection(IOptions <MongoSettings> mongoSettings) { var configuration = mongoSettings.Value; // or use a connection string var settings = new MongoClientSettings() { Credentials = new[] { MongoCredential.CreateCredential( configuration.DatabaseName, configuration.Username, configuration.Password) }, Server = MongoServerAddress.Parse(configuration.ConnectionString) }; var client = new MongoClient(settings); return(client.GetDatabase(configuration.DatabaseName)); }
internal DbContext(string connectionString) { if (database == null) { var pack = new ConventionPack(); pack.Add(new CamelCaseElementNameConvention()); ConventionRegistry.Register("camel case", pack, t => true); this.MapClasses(); var url = MongoUrl.Create(connectionString); IEnumerable <MongoCredential> credentials; if (!string.IsNullOrWhiteSpace(url.Username)) { credentials = new[] { MongoCredential.CreateCredential(url.DatabaseName, url.Username, url.Password) } } ; else { credentials = Enumerable.Empty <MongoCredential>(); } var settings = new MongoClientSettings { ClusterConfigurator = cb => { cb.Subscribe <CommandStartedEvent>(e => { if (!nonLoggedCommandNames.Contains(e.CommandName)) { log.Debug($"{e.CommandName} - {e.Command.ToJson()}"); } }); }, Server = url.Server, Credentials = credentials }; var client = new MongoClient(settings); database = client.GetDatabase(url.DatabaseName); this.CreateIndexes(); } }
private MongoClientSettings settingsList() { //SETTINGS var mongoConnection = new MongoDB.Driver.MongoClient(); var settings = new MongoClientSettings(); settings.ConnectionMode = ConnectionMode.Automatic; settings.VerifySslCertificate = configuration.VerifySsl; settings.UseSsl = configuration.UseSsl; //SET SERVERS var mongoServers = new List <MongoServerAddress>(); foreach (string server in configuration.Servers) { string[] serverVars = server.Split(':'); mongoServers.Add(new MongoServerAddress( serverVars[0].Trim(), Convert.ToInt32(serverVars[1].Trim()) )); } settings.Servers = mongoServers; //SET REPLICASET NAME if (!string.IsNullOrWhiteSpace(configuration.ReplicateSet)) { settings.ReplicaSetName = configuration.ReplicateSet.Trim(); } //SET CREDENTIALS if (!string.IsNullOrWhiteSpace(configuration.AdminDB) && !string.IsNullOrWhiteSpace(configuration.Username) && !string.IsNullOrWhiteSpace(configuration.Password)) { settings.Credentials = new[] { MongoCredential.CreateCredential( configuration.AdminDB, configuration.Username, configuration.Password ) }; } return(settings); }
private DisposableMongoClient CreateMongoClient( CollectionNamespace keyVaultNamespace = null, BsonDocument schemaMapDocument = null, IReadOnlyDictionary <string, IReadOnlyDictionary <string, object> > kmsProviders = null, bool withExternalKeyVault = false, Action <ClusterBuilder> clusterConfigurator = null) { var mongoClientSettings = DriverTestConfiguration.GetClientSettings().Clone(); mongoClientSettings.GuidRepresentation = GuidRepresentation.Unspecified; mongoClientSettings.ClusterConfigurator = clusterConfigurator; if (keyVaultNamespace != null || schemaMapDocument != null || kmsProviders != null || withExternalKeyVault) { var extraOptions = new Dictionary <string, object>() { { "mongocryptdSpawnPath", Environment.GetEnvironmentVariable("MONGODB_BINARIES") ?? string.Empty } }; var schemaMap = GetSchemaMapIfNotNull(schemaMapDocument); if (kmsProviders == null) { kmsProviders = new ReadOnlyDictionary <string, IReadOnlyDictionary <string, object> >(new Dictionary <string, IReadOnlyDictionary <string, object> >()); } var autoEncryptionOptions = new AutoEncryptionOptions( keyVaultNamespace: keyVaultNamespace, kmsProviders: kmsProviders, schemaMap: schemaMap, extraOptions: extraOptions); if (withExternalKeyVault) { var externalKeyVaultClientSettings = DriverTestConfiguration.GetClientSettings().Clone(); externalKeyVaultClientSettings.Credential = MongoCredential.FromComponents(null, null, "fake-user", "fake-pwd"); var externalKeyVaultClient = new MongoClient(externalKeyVaultClientSettings); autoEncryptionOptions = autoEncryptionOptions.With(keyVaultClient: externalKeyVaultClient); } mongoClientSettings.AutoEncryptionOptions = autoEncryptionOptions; } return(new DisposableMongoClient(new MongoClient(mongoClientSettings))); }
public bool Connect() { try { /* ORIGINAL * DbClient = new MongoClient * ( * // https://blog.oz-code.com/how-to-mongodb-in-c-part-2/ * new MongoClientSettings * { * Server = new MongoServerAddress(Ip, 27017), * ServerSelectionTimeout = TimeSpan.FromSeconds(3) * } * ); */ // https://stackoverflow.com/questions/27747503/mongodb-can-connect-from-mongo-client-but-not-from-c-sharp-driver string mongoDbAuthMechanism = "SCRAM-SHA-1"; MongoInternalIdentity internalIdentity = new MongoInternalIdentity(DbName, Id); PasswordEvidence passwordEvidence = new PasswordEvidence(Pw); MongoCredential mongoCredential = new MongoCredential(mongoDbAuthMechanism, internalIdentity, passwordEvidence); MongoClientSettings settings = new MongoClientSettings(); settings.Credential = mongoCredential; MongoServerAddress address = new MongoServerAddress(Ip, 27017); settings.Server = address; DbClient = new MongoClient(settings); Db = DbClient.GetDatabase(DbName); var collections = Db.ListCollections().ToList(); foreach (var item in collections) { // Console.WriteLine(item); } } catch (System.TimeoutException e) { Console.WriteLine("TimeoutException : {0}", e.Message); return(false); } return(true); }
public void TestBadPassword() { var currentCredential = _settings.Credentials.Single(); _settings.Credentials = new[] { MongoCredential.CreatePlainCredential(currentCredential.Source, currentCredential.Username, "wrongPassword") }; var client = new MongoClient(_settings); Assert.Throws <MongoConnectionException>(() => { client.GetServer() .GetDatabase(Configuration.TestDatabase.Name) .GetCollection(__collectionName) .FindOne(); }); }
public void Driver_should_connect_to_AtlasDataLake_with_SCRAM_SHA_256() { RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED"); RequireServer.Check().Supports(Feature.ScramSha256Authentication); var connectionString = CoreTestConfiguration.ConnectionString; var username = connectionString.Username; var password = connectionString.Password; var source = connectionString.AuthSource; var settings = DriverTestConfiguration.Client.Settings.Clone(); settings.Credential = MongoCredential.FromComponents(mechanism: "SCRAM-SHA-256", source, username, password); using (var client = DriverTestConfiguration.CreateDisposableClient(settings)) { client.GetDatabase("admin").RunCommand <BsonDocument>(new BsonDocument("ping", 1)); } }
//생성자, 디비서버에 연결, 데이터 베이스를 받아온다. public MongoDBManager(string pIP, int pPortNum, string pID, string pPW, string pDBName) { m_ipAddress = pIP; m_portNumber = pPortNum; m_userID = pID; m_password = pPW; m_databaseName = pDBName; var credential = MongoCredential.CreateCredential(m_databaseName, m_userID, m_password); var setting = new MongoClientSettings { Credentials = new[] { credential }, Server = new MongoServerAddress(m_ipAddress, m_portNumber) }; m_mongoClient = new MongoClient(setting); m_mongoDatabase = m_mongoClient.GetDatabase(m_databaseName); }
public DatabaseContext(IOptions <Settings> settings) { var cred = MongoCredential.CreateCredential("feedback", "surveyapp", "sunobi1"); var sett = new MongoClientSettings { Server = new MongoServerAddress("ds033047.mlab.com", 33047), Credentials = new List <MongoCredential> { cred } }; //var client = new MongoClient(settings.Value.ConnectionString); var client = new MongoClient(sett); if (client != null) { _database = client.GetDatabase(settings.Value.Database); } }
static void Main(string[] args) { try { MongoClientSettings settings = new MongoClientSettings { ServerSelectionTimeout = new TimeSpan(0, 0, 5), Server = new MongoServerAddress("localhost", 27017), Credentials = new[] { MongoCredential.CreateCredential("loja", "bruno", "xyz123") } }; MongoClient client = new MongoClient(settings); IMongoDatabase database = client.GetDatabase("loja"); IMongoCollection <Cliente> collectionCliente = database.GetCollection <Cliente>("clientes"); // Teste - Inserção de novo Cliente: //Cliente cliente = new Cliente //{ // Nome = "Antonio Pereira", // Email = "*****@*****.**", // Telefone = "99999-8888" //}; //collectionCliente.InsertOne(cliente); // Listagem (leitura) de Clientes: FilterDefinition <Cliente> filtro = Builders <Cliente> .Filter.Empty; List <Cliente> clientes = collectionCliente.Find(filtro).ToList(); clientes.ForEach(c => Console.WriteLine(c)); } catch (TimeoutException e) { Console.WriteLine($"{e.Message}"); } catch (Exception e) { Console.WriteLine($"{e.Message}"); } }
private MongoClient CreateMongoClient(out IMongoDatabase db) { log.LogInformation("Creating MongoClient"); string dbName = Environment.GetEnvironmentVariable("DB_NAME"); if (string.IsNullOrWhiteSpace(dbName)) { log.LogInformation("Could not get environment variable DB_NAME using the default value of 'CatalogDB'"); dbName = "CatalogDB"; } string dbServer = Environment.GetEnvironmentVariable("DB_SERVER"); if (string.IsNullOrWhiteSpace(dbServer)) { log.LogInformation("Could not get environment variable DB_SERVER using the default value of 'localhost'"); dbServer = "localhost"; } string dbUsername = Environment.GetEnvironmentVariable("DB_USERNAME"); string dbPassword = Environment.GetEnvironmentVariable("DB_PASSWORD"); MongoClient client; if (!string.IsNullOrWhiteSpace(dbUsername) && !string.IsNullOrWhiteSpace(dbPassword)) { log.LogInformation(String.Format("Connecting to MongoDB {0}@{1} using {2} user credentials", dbName, dbServer, dbUsername)); var credential = MongoCredential.CreateCredential(dbName, dbUsername, dbPassword); var serverAddress = new MongoServerAddress(dbServer); var settings = new MongoClientSettings { Server = serverAddress, Credential = credential }; client = new MongoClient(settings); } else { log.LogInformation(String.Format("Connecting to MongoDB {0}@{1} without authentication", dbName, dbServer)); client = new MongoClient(dbServer); } db = client.GetDatabase(dbName); return(client); }
public MetaItem() { var settings = new MongoClientSettings { Server = new MongoServerAddress(MongoConfig.Host, MongoConfig.Port) }; if (!string.IsNullOrEmpty(MongoConfig.Username) && !string.IsNullOrEmpty(MongoConfig.Password)) { settings.Credential = MongoCredential.CreateCredential(MongoConfig.Database, MongoConfig.Username, MongoConfig.Password); } var dbClient = new MongoClient(settings); _metaCollection = dbClient.GetDatabase(MongoConfig.Database) .GetCollection <MetaItemModel>(META_COLLECTION_NAME); _bModel = new BuildRepository(); }
public BuildRepository() { var settings = new MongoClientSettings { Server = new MongoServerAddress(MongoConfig.Host, MongoConfig.Port) }; if (!string.IsNullOrEmpty(MongoConfig.Username) && !string.IsNullOrEmpty(MongoConfig.Password)) { settings.Credential = MongoCredential.CreateCredential(MongoConfig.Database, MongoConfig.Username, MongoConfig.Password); } var dbClient = new MongoClient(settings); IMongoDatabase buildDatabase = dbClient.GetDatabase(MongoConfig.Database); _buildCollection = buildDatabase.GetCollection <Build>(BUILD_COLLECTION_NAME); }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { var serviceName = credential.GetMechanismProperty<string>("SERVICE_NAME", "mongodb"); // TODO: provide an override to force the use of gsasl? if (__useGsasl) { return new GsaslGssapiImplementation( serviceName, connection.ServerInstance.Address.Host, credential.Username, credential.Evidence); } return new WindowsGssapiImplementation( serviceName, connection.ServerInstance.Address.Host, credential.Username, credential.Evidence); }
// public methods /// <summary> /// Authenticates the connection against the given database. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> public void Authenticate(MongoConnection connection, MongoCredential credential) { using (var conversation = new SaslConversation()) { var currentStep = _mechanism.Initialize(connection, credential); var command = new CommandDocument { { "saslStart", 1 }, { "mechanism", _mechanism.Name }, { "payload", currentStep.BytesToSendToServer } }; while (true) { var result = connection.RunCommand(credential.Source, QueryFlags.SlaveOk, command, true); var code = result.Response["code"].AsInt32; if (code != 0) { HandleError(result, code); } if (result.Response["done"].AsBoolean) { break; } currentStep = currentStep.Transition(conversation, result.Response["payload"].AsByteArray); command = new CommandDocument { { "saslContinue", 1 }, { "conversationId", result.Response["conversationId"].AsInt32 }, { "payload", currentStep.BytesToSendToServer } }; } } }
/// <summary> /// Determines whether this instance can use the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can use the specified credential; otherwise, <c>false</c>. /// </returns> public bool CanUse(MongoCredential credential) { return credential.Mechanism.Equals(Name, StringComparison.InvariantCultureIgnoreCase) && credential.Identity is MongoExternalIdentity && credential.Evidence is ExternalEvidence; }
// public methods /// <summary> /// Determines whether this instance can authenticate with the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can authenticate with the specified credential; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public bool CanUse(MongoCredential credential) { return credential.AuthenticationProtocol == MongoAuthenticationProtocol.Gssapi && credential.Identity is MongoExternalIdentity; }
/// <summary> /// Determines whether this instance can use the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can use the specified credential; otherwise, <c>false</c>. /// </returns> public bool CanUse(MongoCredential credential) { return _mechanism.CanUse(credential); }
/// <summary> /// Determines whether this instance can use the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can use the specified credential; otherwise, <c>false</c>. /// </returns> public bool CanUse(MongoCredential credential) { return credential.Mechanism.Equals("MONGODB-CR", StringComparison.InvariantCultureIgnoreCase) && credential.Evidence is PasswordEvidence; }
// public methods /// <summary> /// Determines whether this instance can authenticate with the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can authenticate with the specified credential; otherwise, <c>false</c>. /// </returns> public bool CanUse(MongoCredential credential) { return credential.Evidence is PasswordEvidence; }
// public methods /// <summary> /// Determines whether this instance can authenticate with the specified credential. /// </summary> /// <param name="credential">The credential.</param> /// <returns> /// <c>true</c> if this instance can authenticate with the specified credential; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public bool CanUse(MongoCredential credential) { return credential.AuthenticationProtocol == MongoAuthenticationProtocol.Strongest && credential.Evidence is PasswordEvidence; }
/// <summary> /// Initializes the mechanism. /// </summary> /// <param name="connection">The connection.</param> /// <param name="credential">The credential.</param> /// <returns>The initial step.</returns> public ISaslStep Initialize(MongoConnection connection, MongoCredential credential) { return new ManagedCramMD5Implementation(credential.Username, ((PasswordEvidence)credential.Evidence).Password); //return new GsaslCramMD5Implementation(identity); }