Connect Mongodb with username and password - c#

I have mongodb database with username and password, I am trying to access to it from C#, I'm worjking with MongoDBDriver version 2.9.1 from NuGet, I tried the following code:
var client = new MongoClient($"mongodb://usre1:123#localhost/GSCADB");
IMongoDatabase db = client.GetDatabase("GSCADB");
var collection = db.GetCollection<BsonDocument>("GSCALogs");
int TotalFiles = collection.Find(new BsonDocument()).ToList().Count;
but this gives the exception:
Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.

Related

SharePoint App-Only Authentication throwing "The remote server returned an error: (401) Unauthorized."

I am trying to make sharepoint authentication using oAuth or App-Only authentication, but it gives error "The remote server returned an error: (401) Unauthorized."
I am using trial sharepoint tenant.
Here is my code snippets:
Using Client id & Client secret:
string siteUrl = "[Sharepoint-Site-URL]";
//Sharepoint App details
string SPClientId = #"[Client-id]";
string SPClientSecret = #"[Client-secret]";
using (ClientContext context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, SPClientId, SPClientSecret))
{
context.Load(context.Web, t => t.Title);
context.ExecuteQuery();
Console.WriteLine(context.Web.Title);
};
Using AccessToken:
string siteUrl = "[Sharepoint-Site-URL]";
string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));
//Get the access token for the URL.
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
//Create a client context object based on the retrieved access token
using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
{
context.Load(cc.Web, t => t.Title);
context.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
}
enter code here
I referred below articles:
https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs
https://www.c-sharpcorner.com/article/connect-to-sharepoint-online-site-with-app-only-authentication/
This could be SharePoint app-only permissions is disabled in your tenant.
You could run the command to enabel it: Set-SPOTenant -DisableCustomAppAuthentication $false

Connecting to Azure DB with Active Directory-Universal with MFA Support Authentication in C#

I need to access some part of SQL table data from c# console application.I need help to establish the server connection from c#.
DataBase Details:
Server type : Database Engine
Authentication : Active Directory-Universal with MFA support.
Also please do let me know How should I give my Connection properties?
If you don't want to fiddle with tokens or register your C# app as an Azure Application, you can use ODBC or OLE DB with the MSOLEDBSQL driver, which is able to use MFA / ActiveDirectoryInteractive authentication out of the box:
ODBC:
using System.Data.Odbc;
...
OdbcConnection con = new OdbcConnection("Driver={ODBC Driver 17 for SQL Server};SERVER=sqlserver.database.windows.net;DATABASE=database;Authentication=ActiveDirectoryInteractive;UID=user#domain.com");
OLE DB:
using System.Data.OleDb;
...
OleDbConnection con = new OleDbConnection("Provider=MSOLEDBSQL;Data Source=sqlserver.database.windows.net;User ID=user#domain.com;Initial Catalog=database;Authentication=ActiveDirectoryInteractive");
There are 2 different scenarios for logging in to the database.
1) The user logs in with their account and you use that token to authenticate to the SQL database. In this case you can use the standard login popups which will handle the MFA piece for you.
2) Either the user doesn't have privileges on the DB (most standard web apps are an example of this) or you are creating an automated service that needs to log in to the DB. Since the reason for MFA is to have the user complete some action that a machine can't, like entering a code from their cell phone, unattended logins don't work with MFA.
If you are in the second scenario, you will need to create a service principle account that is not protected by MFA for the app to login. Instead of a user name and password, the app gets a unique appId and appSecret to use to access the database. You can add additional protection by placing the secret in Key Vault and limiting the access of that app to just the specific resources it needs to function.
Notice that in this case we aren't passing a user name and password in with the connection string. Instead we get the token separately before adding it to the connection.
string serverName = "myserver.database.windows.net";
string databaseName = "test";
string clientId = "xxxxxx-xxxxx-xxxxx-xxxx-xxxx";
string aadTenantId = "xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxxx";
string clientSecretKey = "xxxxx/xxxxxx/xxxxx";
string sqlConnectionString = String.Format("Data Source=tcp:{0},1433;Initial Catalog={1};Persist Security Info=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False", serverName, databaseName);
string AadInstance = "https://login.windows.net/{0}";
string ResourceId = "https://database.windows.net/";
AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(AadInstance, aadTenantId));
ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
DateTime startTime = DateTime.Now;
Console.WriteLine("Time " + String.Format("{0:mm:ss.fff}", startTime));
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(ResourceId, clientCredential).Result;
DateTime endTime = DateTime.Now;
Console.WriteLine("Got token at " + String.Format("{0:mm:ss.fff}", endTime));
Console.WriteLine("Total time to get token in milliseconds " + (endTime - startTime).TotalMilliseconds);
using (var conn = new SqlConnection(sqlConnectionString))
{
conn.AccessToken = authenticationResult.AccessToken;
//DO STUFF
}

Authenticate User on MongoDB with .NET Driver 2.4

The following code works as it should do, if the server is running and if the usename and password are correct. However, if i give a wrong username or password, it does not give me feedback, but only runs into a timeout when calling the Count method.
MongoClientSettings setts = new MongoClientSettings()
{
Server = new MongoServerAddress("127.0.0.1", 27017),
Credentials = new MongoCredential[] { MongoCredential.CreateCredential("TestDatabase", "username", "password") }
};
this.client = new MongoClient(setts);
this.client.Cluster.DescriptionChanged += this.ClusterDescriptionChanged;
var database = this.client.GetDatabase("TestDatabase");
var collection = database.GetCollection<BsonDocument>("SimpleCollection");
var count = collection.Count(MongoDB.Driver.FilterDefinition<BsonDocument>.Empty);
How do i get error messages from the driver and how can i check if it's the connection, the user or the password that does not fit?
PS: The driver API has changed a lot since 2.0 in Jan.2016, which means that most webtutorials and posts on this site no longer work for the current version.
Once you get the client, you can check if the connection is successful
var server = client.GetServer();
server.Ping();
Also it is always a good idea to enclose your code in a try catch with timeout exception because that is expected.
for more info on this you can refer MongoDB C# Driver check Authentication status & Role

Connect to DocumentDB using MongoDb API

I have following problem
While I am trying to connect to the DocumentDB database using MongoDb API:
var cstring = "mongodb://textadmin:<MY VERY SECRET PASSWORD>#<MY SERVER>.documents.azure.com:10250/?ssl=true"
var client = new MongoDB.Driver.MongoClient(cstring)
var server = client.GetServer()
server.Ping()
I have the following error:
Authentication failed because the remote party has closed the transport stream
Any ideas what to change in the code (or in the server settings perhaps)?
You need to set EnabledSslProtocols to TLS12 to be able to connect to DocumentDB using MongoDB API. By default, the Mongo C# driver does not use TLS1.2 causing the connection to fail during SSL handshake.
Sample Code:
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress(host, 10250);
settings.UseSsl = true;
settings.SslSettings = new SslSettings();
settings.SslSettings.EnabledSslProtocols = SslProtocols.Tls12;
MongoIdentity identity = new MongoInternalIdentity(dbName, userName);
MongoIdentityEvidence evidence = new PasswordEvidence(password);
settings.Credentials = new List<MongoCredential>()
{
new MongoCredential("SCRAM-SHA-1", identity, evidence)
};
MongoClient client = new MongoClient(settings);
Reference: https://azure.microsoft.com/en-us/documentation/articles/documentdb-mongodb-samples/

Error when calling any method on Service Management API

I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!

Categories

Resources