MySQL authentication error with .NET connector 8.0 - c#

When I use the .NET connector with my console application ( .NET 4.7.2) to connect to a remote MySQL server I get the error below.
MySql.Data.MySqlClient.MySqlException (0x80004005): Authentication to host 'XX.XXX.XXX.XX' for user 'YYYYYYY' using method 'mysql_native_password' failed with message: Access denied for user 'YYYYYYY'#'ZZZ.ZZZ.ZZZ.ZZZ' (using password: YES) ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'YYYYYYY'#'ZZZ.ZZZ.ZZZ.ZZZ' (using password: YES)
I thought it has to do with the password and reset it and it still didn't work, have been able to connect to it successfully using "HeidiSQL" and "MYSQL Workbench" and so there doesn't seem to be any problem with password perse at the server end.
Please note that I am using MySQL with SSL connection as demonstrated by sample code below.
var builder = new MySqlConnectionStringBuilder();
builder.Server = "XX.XXX.XXX.XX";
builder.UserID = "YYYYYYY";
builder.Password = "PPPPPPPPPPP";
builder.SslCa = #"D:\certs\server-ca.pem";
builder.SslKey = #"D:\certs\client-key.pem";
builder.SslCert = #"D:\certs\client-cert.pem";
builder.SslMode = MySqlSslMode.VerifyFull;
builder.Database = "noodlewatch";
builder.Port = 3306;
builder.Pooling = true;
builder.UseCompression = true;
MySqlConnection conn = new MySqlConnection(builder.ConnectionString);
Any ideas on what needs to be done here?
I have tried a lot of permutations and combinations with the "MySqlConnectionStringBuilder" but it always ends the same way. It definitely is not a "password" issue as I can connect to it with standard MySQL clients.
Edit:
This is not a duplicate of that other question with a similar error because that one had to do with user grants, I am able to connect to the same remote server with "HeidiSQL" and "MySQL Workbench" from the same client machine so it's quite obviously not something to do with privilege issues for the user.
Edit:
The . NET application and the other client applications are residing on the same Windows 10 machine.

Related

Connect to Postgres DB in AWS using IAM Authentication with SSL

I have an RDS instance running Postgres which has IAM Authentication enabled. I can successfully connect using an IAM token via powershell, but I'm having trouble with certificates when trying to connect using the Npgsql library with C# (targeting .Net Core 3.1) from Visual Studio 2019 Version 16.8.5 (on .Net Framework 4.8).
Note, I've been referencing this AWS page, which gives download links for the certificates.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html
I've also been referencing this page to guide me through getting this set up.
https://aws.amazon.com/premiumsupport/knowledge-center/rds-postgresql-connect-using-iam/
I can connect with PowerShell, using:
$ENV:RDSHOST="my-postgres-instance.eu-west-1.rds.amazonaws.com"
$ENV:PGPASSWORD="$(aws rds generate-db-auth-token --hostname $ENV:RDSHOST --port 5432 --region eu-west-1 --username my_db_user)"
psql -h $ENV:RDSHOST -p 5432 "sslmode=verify-full sslrootcert=rds-ca-2019-root.pem dbname=my_db user=my_db_user password=$ENV:PGPASSWORD"
However when I try to open a connection with C# using the Npgsql library with the code below, I get an exception:
var host = "my-postgres-instance.eu-west-1.rds.amazonaws.com";
var port = 5432;
var user = "my_db_user";
var token = RDSAuthTokenGenerator.GenerateAuthToken(RegionEndpoint.EUWest1, host, port, user);
var builder = new NpgsqlConnectionStringBuilder
{
Host = host,
Port = port,
Database = "my_db",
Username = user,
Password = token,
SslMode = SslMode.Require,
RootCertificate = #"C:\Path\To\Cert\rds-combined-ca-bundle.pem",
};
using (var conn = new NpgsqlConnection(builder.ConnectionString))
{
conn.Open();
}
Npgsql.NpgsqlException: 'Exception while performing SSL handshake
AuthenticationException: The remote certificate is invalid according to the validation procedure.
It's worth noting that I can connect setting TrustServerCertificate = true, however as I understand it, this is masking the problem and reducing security, and is not advisable.
The AWS page linked above mentions:
If your application is on Microsoft Windows and requires a PKCS7 file, you can download the PKCS7 certificate bundle. This bundle contains both the intermediate and root certificates at https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.p7b.
I've tried specifying this p7b file as the NpgsqlConnectionStringBuilder.ClientCertificate, but this causes a different exception when opening the connection:
Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Cannot find the original signer.'
Anyone able to help me understand how to connect? It's worth noting that I'm not very familiar with detting up SSL connections or dealing with certificates, so bear that in mind.

SQL Server - Difference between errors 18456, 4064 and 4060

I have a windows application written in vb.net. It interacts with SQL Server and we can create users from it on the server. From the application I disabled some users (it runs DROP USER (loginName) command behind the scenes). There was some strange behavior observed while handling SqlException in this case. While trying to login into SQL server (both through code and SQL server management studio) with disabled users, for some users it was giving a 4064 error code whereas for others it was giving 18456.
Here are some more details:
SQL Server version - 2016 SP1. Mixed mode authentication.
There are a couple of DBs other than master.
On SQL Server in sys.syslogins table - For users for whom I got a 4064 error, the default DB was
master. For those who's default DB was not master, I got 18456 error.
In code - For some reason, while catching SqlException in code, for
users getting 4064 error while logging on SQL, I get 4060 error. For
users with 18456 code, it works fine and I get the same error code in
Exception.
Entries are in sys.syslogins, sys.sysusers table (as far as sys
tables go).
As per the official description given:
MSSQLSERVER_4064:
The SQL Server login was unable to connect because of a problem with its
default database. Either the database itself is invalid or the login lacks
CONNECT permission on the database.
and
MSSQLSERVER_18456:
When a connection attempt is rejected because of an authentication failure that involves a bad password or user name, a message similar to the following is returned to the client: "Login failed for user ''. (Microsoft SQL Server, Error: 18456)".
Could not find an official detailed description for 4060 except this:
Cannot open database "%.*ls" requested by the login. The login failed.
Several forums say its related to login failure. I tried looking for some data on difference between nature of the failures for these 3 codes, but couldn't find one.
What are the scenarios in which we can get 4064 or 4060 codes? Are there any overlapping fail cases where we can get either of these (like for 18456 and 4060)?
EDIT: Here is the code for creating the connection:
connection = new SqlConnection()
Dim builder As New SqlConnectionStringBuilder
builder.DataSource = "localhost"
builder.InitialCatalog = "DatabaseA"
builder.ConnectTimeout = 120
builder.UserID = username
builder.Password = Encrypt(password)
connection.ConnectionString = builder.ConnectionString

Error when trying to connect to SQL Server from program on remote computer

I am trying to set up a system for employees to use in the office so they can run certain programs from a website.
They will be able to login and go to a reports page an click a button to run a reports program on the utility server. The program will connect to SQL Server to get the login information and then login to another site and programmatically create the reports and download them.
If I run the program as a stand alone program on the server it runs fine. I even have it running as a scheduled task on the server itself and it runs fine. It is only when I try to run the program from the website that I get the error stating the program but it is terminated due to an unhandled exception. Here is the stack trace from the error in the event viewer.
Application: Trending Reports.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient.SqlException
Stack:
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource1, System.Data.Common.DbConnectionOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(System.Threading.Tasks.TaskCompletionSource1<System.Data.ProviderBase.DbConnectionInternal>)
at System.Data.SqlClient.SqlConnection.TryOpen(System.Threading.Tasks.TaskCompletionSource1)
at System.Data.SqlClient.SqlConnection.Open()
at Trending_Reports.Program.Main(System.String[])
Here is the code I am using to start the program.
var processToRun = new[] { #"D:\test\Trending Reports.exe" };
var connection = new ConnectionOptions();
connection.Impersonation = System.Management.ImpersonationLevel.Impersonate;
connection.Username = "Username";
connection.Password = "password";
var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "Server"), connection);
wmiScope.Connect();
var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);
The program itself is using multi-threading. Could this be causing the issue? Or could it be a user issue to where its not using my user profile on the remote computer?
Have you configured the SQL server to accept remote connections? This is a common cause for errors.
You can follow the following steps:
Enable remote connections on the instance of SQL Server that you want
to connect to from a remote computer.
Configure SQL server to listen on static port
Turn on the SQL Server Browser service.
Configure the firewall to allow network traffic that is related to
SQL Server and to the SQL Server Browser service.
This link here has a step-by-step tutorial with pictures (Microsoft SQL Server 2012 Express).

OleDBConnection error Database Server Not Found C#

I'm trying to connect to a remote SQL Anywhere 10 database server using the following connection string but receiving a "Database Server Not Found" error.
OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;ENG=dental;DBN=dentserv;
LINKS=tcpip(host=192.168.1.100,PORT=2638);
Integrated Security = True; User ID = dba; PWD = sql");
Using the same code, I can connect to a local database that is setup the same way as the remote server I'm attempting to connect to without any issue:
OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;Data Source = dental;
Database=dental;Integrated Security = True; User ID = dba; PWD = sql");
I've added and removed multiple variables within the string to troubleshoot to see if there was anything missing (ENG instead of Data Source, with and without DBN, DSN, etc.), most seem to be interchangeable but always throwing the same error of no server.
For some additional information, I am able to connect to this server database using a different database management tool using the same port IP credentials with no issue. It's Database URL is: jdbc:sybase:Tds:192.168.1.100:2638?ServiceName=
Connection String:
DBN=DENTSERV;DSN=DENTAL;UID=DBA;PWD=SQL
Any thoughts? I've been working on this for awhile with no further progress. Any insight will be much appreciated!
The host (host=192.168.1.100); appears to be a private IP (IP for your local network), you cant use that for remote access you may use a Public IP also the server need to be configured for remote access.

Can not connect to secure phpmyadmin through my c# code

I can not open a new connection through my code to my digitalocean server.. It's my first account and will be my first online database program.. here's what I did
after creating an account on digitalocean I've created a droplet and installed LAMP and secure phpmyadmin by following the installation tutorials..
I've given an IPv4 Address: xx.xxx.xx.xxx
when I typein xx.xxx.xx.xxx/phpmyadmin to my browser it asks for username and password, than comes the phpmyadmin screen which asks for username root and it's password
I've created a new database= TestApp and users table..
and then I made a very basic program via c#, I have a textbox and a button and the code is as follows:
string conString = "Server=xxx.xxx.xxx.xx;Database=TestApp;Uid=root;pwd=_______";
MySqlConnection newCon = new MySqlConnection(conString);
string insertCommand = "INSERT INTO TestApp.users(isim) VALUES (?isim)";
MySqlCommand cmd = new MySqlCommand(insertCommand, newCon);
newCon.Open();
cmd.Parameters.Add("?isim", txtpost.Text);
cmd.ExecuteNonQuery();
newCon.Close();
when I run the program it gives the following error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Unable to connect to any of the specified MySQL hosts.
how do I solve my issue?
I don't know DigitalOcean, but I am assuming that the virual server has been configured to only allow web traffic into it (i.e. ports 80 and 443, which is why phpmyadmin works).
Your C# code (is it's not on the server itself) will need to access the MySQL port which by default is 3306. You will need to find instructions on DigitalOcean for opening this up.

Categories

Resources