788

I am experiencing an error when connecting MY DB which is in VM Role (I have SQL VM Role) from Azure Website. Both VM Role and Azure Website are in West zone. I am facing the following issue:

SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)]

I am able to connect to my DB using SSMS. Port 1433 is open on my VM role. What is wrong with my connection?

31 Answers 31

1417

This answer provides an explanation and stop gap, but also offers some better recommendations including purchasing and installing a proper certificate.

Please see also the other highly voted answers in this thread, including this answer by Alex From Jitbit, about a breaking change when migrating from System.Data.Sql to Microsoft.Data.Sql (spoiler: Encrypt is now set to true by default).


You likely don't have a Certificate Authority(CA)-signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string (also not recommended):

TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.

Long term, I'd recommend leveraging Let's Encrypt to get a CA-signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".

11
  • 4
    sorry my bad, TTrusted_Connection=False was set in connection string. setting it true works for me. Thanx anyway Commented Jul 24, 2013 at 8:59
  • 23
    It is not good to advise setting TrustServerCertificate to true--this disables certificate checking. That's no better than just setting Encrypt to false! Commented Mar 30, 2017 at 19:34
  • 13
    The advice given "TrustServerCertificate=True" in this answer might make the problem go away, but it's terrible advice. Fix the cause, NOT the symptoms. The other part of the answer suggesting installing a CA signed cert is the way to go. Commented Oct 1, 2018 at 10:53
  • 6
    In newer versions of SSMS you find a little option called "Trust server certificate" in the "Connection Properties" Tab. Checking this boy has the same effect as the commands listed above.
    – verfluecht
    Commented Dec 18, 2018 at 7:58
  • 9
    I would like to point out that there are cases when we definitely don't care whether "a hacker can intercept your sql traffic", such as for instance, you're in development, and the server you're connecting to is localhost...
    – neminem
    Commented Sep 13, 2023 at 18:46
451
Answer recommended by Microsoft Azure Collective

I decided to add another answer, because this post pops-up as the first Google result for this error.

If you're getting this error after January 2022, possibly after migrating from System.Data.SqlClient to Microsoft.Data.SqlClient or just updating Microsoft.Data.SqlClient to version 4.0.0 or later, it's because MS has introduced a breaking change:

https://docs.microsoft.com/sql/connect/ado-net/introduction-microsoft-data-sqlclient-namespace?view=sql-server-ver15#breaking-changes-in-40

Breaking changes in 4.0

Changed Encrypt connection string property to be true by default.

The default value of the Encrypt connection setting has been changed from false to true. With the growing use of cloud databases and the need to ensure those connections are secure, it's time for this backwards-compatibility-breaking change.

Ensure connections fail when encryption is required

In scenarios where client encryption libraries were disabled or unavailable, it was possible for unencrypted connections to be made when Encrypt was set to true or the server required encryption.

The change was made in this SqlClient pull-request in August 2021, where there is additional discussion about the change.

The quick-fix is to add Encrypt=false to your connection-strings.

5
  • 24
    The same also happens when using Entity Framework Core 7 (currently in preview), and the same fix works perfectly. Thanks for sharing
    – AFract
    Commented Mar 31, 2022 at 9:37
  • 5
    The solution (as opposed to a quick fix) is to get a real certificate, either from Let's Encrypt or a private CA Commented Apr 21, 2022 at 11:35
  • funny thing is that even you roll back from ef core 7 to ef core 6 the error still pops up.
    – akd
    Commented Oct 27, 2022 at 15:20
  • 6
    Adding the modified ConnectionStrings part if someone is wondering how to fix this. "ConnectionStrings": { "DefaultConnection": "Server=.;Database=Reactivity;Trusted_Connection=True;Encrypt=False" } Commented Dec 28, 2022 at 22:07
  • 1
    quick fix is what exactly what I was looking for... anyway I think that Microsoft should better leave the default options, and let people decide when (and if) to eventually improve their own connections by using encryption, instead of changing it and create a panic... Commented Jan 19, 2023 at 19:00
255

If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated" If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated"

6
  • 39
    It is not a bad advice per se. I would say that you can use it when you need to connect to a development server and do your job, such as coding. As a software developer I constantly struggle with DevOps who don't have time to fix things quickly and I can't afford to waste precious time against deadlines. Weighing data exposure turning off this option depends a lot of your environment, if it's local or remote, how admins set it up, IP restrictions and it can be easily mitigated with other workarounds. You can't say it's a bad advice without having a bit of information about your infrastructure.
    – OrizG
    Commented Dec 29, 2018 at 1:29
  • 1
    @OrizG I have a SQL Server installed on a local machine, and I use it for personal projects. At the moment, I don't want to spend a penny with it, so I got myself a free host and tried to configure the server in a way that I Ca-sign the certificates, and exchange them between the server and clients I'll be using to access it. However, because of the free host, I didn't manage to do that with Let's Encrypt. What exactly are the disadvantages of this solution, in comparison with properly doing the certificate exchange, with trusted CA signed certificates?
    – ccoutinho
    Commented Feb 20, 2020 at 23:29
  • What if im using EXCEL to get data from SQL Server DB? i have no setting like that
    – kucluk
    Commented Oct 12, 2021 at 4:36
  • @kucluk See answer from "Alex from Jitbit" above: Add Encrypt=False to your connection-strings
    – kevinarpe
    Commented Jan 31, 2023 at 5:35
  • You are an absolute rock star! This would have driven me around the bend after how many others I've ran into today, leading up to this exact issue (and resolution) Thank you kindly Commented Apr 13, 2023 at 4:33
98

If you're seeing this error message when attempting to connect using SSMS, add TrustServerCertificate=True to the Additional Connection Parameters.

2
  • 30
    Mitch, you made this same comment on three answers to this question. It might be helpful to other readers if you provided some substantive information or link as to why this is "really, really bad advice."
    – Shoeless
    Commented Oct 2, 2018 at 15:26
  • 1
    @Shoeless the same reason it's bad in any other certificate scenario -- it enables MITM attacks -- though with SQL Server, you're doing some infrastructure centric setup anyway, so MITM can be mitigated in other ways (i.e. restricting IP access and ensuring that the two machines are directly connected on the same network, etc.) -- Still, it's a bit cringe, but hey, Apple shipped MITM enabled devices for a couple of years before bothering to fix anything? -- So, it's probably fine. 😆 Commented Aug 19, 2020 at 21:43
61

I was getting this message in Entity Framework migrations. I was able to connect with Win Auth to the Sql Server and create table manually. But EF wouldn't work. This connection string finally worked

Server=MyServerName;Database=MyDbName;Trusted_Connection=SSPI;Encrypt=false;TrustServerCertificate=true
2
  • 2
    I uninstalled, installed again, repaired, restarted all of my SQL Server instances, several times. The same with SQL Server integration for VS22. The same with SSMS. Nothing worked. Copying and pasting the error from PMC brought me here. The solution was in these answer(s). Not even ChatGPT was able to help (probably because this is a recent issue). Thank you SO community.
    – carloswm85
    Commented May 20, 2023 at 1:57
  • When I tried to update EDMX with a change made in the DB, (regarding the import of a function) only this helped and there was another solution that didn't help. I'm on my development machine and there's nothing to do with security.
    – Developer
    Commented Nov 30, 2023 at 18:42
25

I added this 2 lines to the ConnectionString and it worked

Trusted_Connection=True
TrustServerCertificate=True
21

If you want to absolutely abandon all security:

While the general answer was in itself correct, I found it did not go far enough for my SQL Server Import and Export Wizard orientated issue. Assuming you have a valid (and automatic) Windows Security based login:

ConnectionString

Data Source=localhost; 
Initial Catalog=<YOUR DATABASE HERE>; 
Integrated Security=True; 
Encrypt=True; 
TrustServerCertificate=True; 
User Instance=False

That can either be your complete ConnectionString (all on one line), or you can apply those values individually to their fields.

3
  • 1
    Well you basically disabled all security by using TrustServerCertificate=True; so of course this will work!
    – Zimano
    Commented Sep 12, 2022 at 13:12
  • 1
    Fortunately it was confined only to localhost, but disabling all secure was the ultimate goal. Commented Sep 15, 2022 at 7:46
  • That's true, it's not that big of a deal in localhost settings :-)
    – Zimano
    Commented Sep 15, 2022 at 9:08
20
PM> Scaffold-DbContext "Server=localhost;Database=BookStoresDB;Trusted_Connection=True;TrustServerCertificate=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Using "TrustServerCertificate=True" solved Error "A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)"

1
  • 2
    TrustServerCertificate=True resolved the issue, Thank you !!! Commented May 8, 2023 at 9:19
19
"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-O5SR0H0\\SQLEXPRESS;Database=myDataBase;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}
18

If you use EF Core 7 there is a breaking change that explained in the official Microsoft doc https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/breaking-changes#encrypt-defaults-to-true-for-sql-server-connections

1
  • 3
    Thank you. After I added "Encrypt=False" in my connection string, it worked!!!
    – Petronius
    Commented Dec 28, 2022 at 20:12
14

If You are trying to access it through Data Connections in Visual Studio 2015, and getting the above Error, Then Go to Advanced and set TrustServerCertificate=True for error to go away.

1
  • 11
    It is not a bad advice per se. I would say that you can use it when you need to connect to a development server and do your job, such as coding. As a software developer I constantly struggle with DevOps who don't have time to fix things quickly and I can't afford to waste precious time against deadlines. Weighing data exposure turning off this option depends a lot of your environment, if it's local or remote, how admins set it up, IP restrictions and it can be easily mitigated with other workarounds. You can't say it's a bad advice without having a bit of information about your infrastructure.
    – OrizG
    Commented Dec 29, 2018 at 1:30
14

Add Encrypt=False to your connection string and that's it

10

In my case, I have changed multiple times in appsettings.json, but not in the development version of appsettings.Develpment.json. After change the development version of appsettings. it worked fine.

"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-M08SV8P;Database=ActivityProject;Trusted_Connection=True;TrustServerCertificate=True;"
},

enter image description here

0
9

In my case, it wasn't enough to extend the connection string by
Encrypt=false;TrustServerCertificate=true;

I still had to type in the NuGet console:

update-database -verbose

8

Guide on how to make encrypt = False using SSMS. Only for local development purposes. Not recommended for production use cases.

  1. Click on options>>
  2. As shown in the pic, de-select the Encrypt connection.
  3. Click connect. <<** boom **>>.

enter image description here

0
7

When you are using SqlPackage.exe, the Encrypt=False in your connectionstring is ignored.

Add /TargetTrustServerCertificate:true to the SqlPackage command to fix this issue.

1
  • Encrypt=False still works for me using SqlPackage.exe
    – apr
    Commented Jun 3 at 9:29
6

For those who don't like the TrustServerCertificate=True answer, if you have sufficient access you can export the SQL Server certificate and install where you're trying to connect from. This probably doesn't work for a SQL Server self-generated certificate but if you used something like New-SelfSignedCertificate you can use MMC to export the certificate, then MMC on the client to import it.

On SQL Server:

  • In MMC add the certificate Snap-In
  • Browse to Certificates > Personal > Certificate
  • Select the new certificate, right-click, and select All Tasks > Manage Private Keys (this step and the following is part of making the key work with SQL server)
  • Add the identity running SQL Server (look the identity up in Services if in doubt) with READ permission.
  • Select the new certificate, right-click, and select All Tasks > Export...
  • Use default settings and save as a file.

On the client:

  • Use MMS with the same snap-in choices and in Certificates > Trusted Root Certification Authorities right-click Certificates and select All Tasks > Import...
  • Import the previously exported file

(I was doing everything on the same server and still had issues with SSMS complaining until I restarted the SQL instance. Then I could connect encrypted without the Trust... checkbox checked)

6

If you use Version 18 and access via pyodbc, it is "TrustServerCertificate=yes", you need to add to the connection

1
  • Just what I needed to get my connection string to work, thank you. Commented Jan 24, 2023 at 22:01
6

In simple this is enough,if you are running locally

"ConnectionString": "Data Source=(local);Initial Catalog=BlazorDashboardDb;TrustServerCertificate=True;Integrated Security=True;", 1

TrustServerCertificate makes SSL handling Integrated Security makes windows validation,if sql authentication the add parameter as "User ID=adminUsername;Password=adminSecretPasswordwhatever"

TO cover all sceanrio then below helps "Data Source=(local);Initial Catalog=BlazorDashboardDb;TrustServerCertificate=True;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=true;Encrypt=True;"

Trusted_Connection is for trusting the mode of connection Encrypt is for crednetials

Connecting to server(az-sql) ex: "Server=tcp:firstserver.database.windows.net,1433;Initial Catalog=First;Persist Security Info=False;User ID=adminUsername;Password=adminSecretPasswordwhatever;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"

5

I got this Issue while importing Excel data into SQLDatabase through SSMS. The solution is to set TrustServerCertificate = True in the security section

4

Got hit by the same issue while accessing SQLServer from IIS. Adding TrustServerCertificate=True did not help.

Could see a comment in MS docs: Make sure the SQLServer service account has access to the TLS Certificate you are using. (NT Service\MSSQLSERVER)

Open personal store and right click on the certificate -> manage private keys -> Add the SQL service account and give full control.

Restart the SQL service. It worked.

4

If you are using any connection attributes mentioned in the answers, the values accepted are yes/no , if true/false doesn't seem to work.

TrustServerCertificate - Accepts the strings "yes" and "no" as values. The default value is "no", which means that the server certificate will be validated.

Using ODBC 18.0 - hope it helps.

Connection String Attributes

3

I had the same issue after migrating a project from .NET 5 to .NET 6. I have tried suggested solutions (either TrustServerCertificate=True or Encrypt=False) and they worked as expected but I had a limitation to not change connection string. So if that is the case, you can still use System.Data.SqlClient as a nuget package. Like explained here it is still maintained but all the new stuff will go to Microsoft.Data.SqlClient.

2

If you have created an ODBC connection to the server (using ODBC Driver 18 for SQL server) in ODBC settings (32 or 64), configure the connection and press Next 3 times. In the final screen, there is a "Trust server certificate" checkbox in the middle. Set it to checked. That will do the trick. Adding "TrustServerCertificate=True" to the connectionstring as suggested in other answers did not work for me.

ODBC Data Sources (32 or 64)

2

Short notice. If you're using AWS RDS you can get the certificates from truststore.pki.rds.amazonaws.com. Details with particular links can be found in this documentation: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html.

Simply download the appropriate certificate and install it on your host.

1

I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).

1

Alternatively, create a Service Master Key (SMK) based on an exported server certficate from your MMC console - export as a pfx with a password. Using that certificate, engage in the following steps

CREATE MASTER KEY ENCRYPTION BY PASSWORD='Password1234!@#$'

From you exported certificate, run the batch file

@echo off 
echo Create a new password at the pop-up. 
echo This is NOT the same as the one you provided above. 
echo You'll be asked to create, confirm and re-enter the password (total 3 times) 
echo Creating Certificate (CER) and Key (PVK). 
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\x64\makecert.exe" -sv %1.pvk -n "CN=%2" %1.cer 
echo On prompt, again (4th and last time) provide the password you just created. 
echo Merging the two files into a PFX now. 
"C:\Program Files (x86)\Windows Kits\8.0\bin\x64\pvk2pfx.exe" -pvk %1.pvk -spc %1.cer -pfx %1.pfx -po %3

CREATE YOUR ASSYMETRIC KEY

CREATE CERTIFICATE MYDB_ASYMMETRIC_CA_KEY  FROM FILE='C:\MYDB_ASSYMETRIC_CA_KEY.cer'
  WITH PRIVATE KEY(FILE='C:\ MYDB_ASSYMETRIC_CA_KEY.pvk'
  DECRYPTION BY PASSWORD='Password1234!@#$'); 

For redundancy, check that your master key is in place... it is a must

ALTER MASTER KEY REGENERATE WITH ENCRYPTION BY PASSWORD='Password1234!@#$'

NOW CREATE THE ACTUAL KEY

CREATE CERTIFICATE MYDB_ASYMMETRIC_CA_KEY FROM FILE='c:\MYDB_ASYMMETRIC_CA_KEY.cer' 
WITH PRIVATE KEY (FILE='C:\MYDB_ASYMMETRIC_CA_KEY.pvk',
DECRYPTION BY PASSWORD='Password1234!@#$');

ALWAYS ALWAYS Backup your certificate in the event you need to move to another server. You'll need it to decrypt your backup files

BACKUP CERTIFICATE MYDB_ASYMMETRIC_CA_KEY TO FILE='MYDB_ASYMMETRIC_CA_KEY_BACKUP.bkp' 
WITH PRIVATE KEY(FILE='MYDB_ASYMMETRIC_CA_KEY_BACKUP.bkp',
ENCRYPTION BY PASSWORD='Password1234!@#$'); 

CREATE Database Level Encryption to wrangle in your certificate

CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM=AES_256
ENCRYPTION BY SERVER CERTIFICATE MYDB_ASYMMETRIC_CA_KEY

Check the steps above before going to the next step as from here on in, your database will be encrypted with an Assymentric Key - if you haven't backed it up (the key) and you try to restore from another server, it won't be possible without all the above steps in place.

On another database - for example a Staging Database - Restore the Master key from the certificate.

You have your Service Master Key in place, to encrypt the database, you need to encrypt the Database Master Key as this allows the export of the database to another server using the certificate you've created above.

TESTING THE Certificate by importing to another server

RESTORE MASTER KEY FROM FILE='C:\ MYDB_ASSYMETRIC_CA_KEY_BACKUP'
 DECRYPTION BY PASSWORD='Password1234!@#$', ENCRYPTION BY PASSWORD='Password1234!@#$'
 ,[FORCE]

Check to see if the Content exists on the alternate server (this will work on the primary as well)

USE [AUTHORIZATION]; 
 IF NOT EXISTS ( SELECT
 1
 FROM
 sys.dm_database_encryption_keys
 WHERE
 DB_NAME(database_id) = DB_NAME() )
 SELECT
 DB_NAME() AS [Database Name]
 ,'No database encryption key present, no encryption' AS [Encryption
 State] 
 ELSE
 SELECT
 DB_NAME(database_id) AS [Database Name]
 ,CASE encryption_state
 WHEN 0 THEN 'No database encryption key present, no encryption'
 WHEN 1 THEN 'Unencrypted'
 WHEN 2 THEN 'Encryption in progress'
 WHEN 3 THEN 'Encrypted'
 WHEN 4 THEN 'Key change in progress'
 WHEN 5 THEN 'Decryption in progress'
 WHEN 6 THEN 'Protection change in progress'
 END AS [Encryption State]
 FROM
 sys.dm_database_encryption_keys
 WHERE
 DB_NAME(database_id) = DB_NAME(); 
1
  • This question has nothing to do with database encryption or SMK, it's about the connection encryption, which uses a normal TLS certificate with a SAN/DNS name. Commented Jan 24 at 14:27
0

I was getting the same error when trying to connect to MS SQL Server instance hosted on Google Cloud Platform using SSMS with unchecked Trust server certificate under the connection properties tab. I managed to trust the certificate by importing the GCP's provided certificate's authority to my local computer's list of Trusted Root Certification Authorities.

Read full description and resolution here.

0

In addition to the detailed information provided in other answers, if one is using PowerShell and needs to connect using the Invoke-Sqlcmd cmdlet then one of the easiest/quickest options to overcome this error is to use the -TrustServerCertificate switch:

Note: Just the -TrustServerCertificate switch without "=True".

For example:

invoke-sqlcmd -ServerInstance $your_srv -Query $your_query -ConnectionTimeout 5 -TrustServerCertificate
  • above query assumes you're using AD/Windows Authentication.

Disclaimer: the installation of the appropriate certificates should not be compromised in order to maintain security.

HTH.

2
  • Might be easier/quicker, but it's more insecure. Also not adding any more real info than the top two answers. Commented Jan 24 at 14:29
  • @Charlieface, see the disclaimer added to address your comment. Commented Jan 25 at 10:33
0

If this issue you are encountering in .NET 8/C# environment:

When you are checking for 'TrustServerCertificate=True', make sure you check on both SQLServer table(related to your connection string) & also the 'appsettings.json' of your application project where you suspect an issue (mostly it has do be with the security related project of your application or check your logs to find the root path)

If that is missing, add it so it is in both places.

Not the answer you're looking for? Browse other questions tagged or ask your own question.