Breaking changes in Microsoft.Data.SqlClient 4.0--- Encrypt defaults to true for SQL Server connections

Programming, error messages and sample code
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.)]

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. For more detail, you can refer to:

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

Old behavior

SqlClient connection strings use Encrypt=False by default. This allows connections on development machines where the local server does not have a valid certificate.

New behavior

SqlClient connection strings use Encrypt=True by default. This means that:

  • The server must be configured with a valid certificate
  • The client must trust this certificate

If these conditions are not met, then the SqlException will be thrown. 

 

If you use EF Core 7.0 (EF7), you may get the same error also due to the breaking change in Microsoft.Data.SqlClient package. You can get more detail info here:

https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/breaking-changes

Mitigations

There are three ways to proceed:

  1. Install a valid certificate on the server. Note that this is an involved process and requires obtaining a certificate and ensuring it is signed by an authority trusted by the client.
  2. If the server has a certificate, but it is not trusted by the client, then TrustServerCertificate=True allows bypassing the normal trust mechanisms.
  3. Explicitly add Encrypt=False to the connection string.
Please do not worry, all of our DB servers have a valid certificate installed. So if your application connects to your online DB on our end, you would not get such an issue. However, if your application is connected to an external DB server that does not have a valid certificate installed, then you will get sql exception as above.
 
You can safely trust the server certificate by adding TrustServerCertificate=True OR Encrypt=False in the database ConnectionString to wave such issue or contact your DB server provider to import a valid certificate to their DB server.