SSL
HttpClient
Untrusted Certificates
Security
Networking

HttpClient untrusted SSL certificates: DangerousAcceptAnyServerCertificateValidator

Codemia Knowledge Hub ·

To allow untrusted SSL certificates with HttpClient in C#, set a ServerCertificateCustomValidationCallback on HttpClientHandler that returns true; the simplest version uses the built-in HttpClientHandler.DangerousAcceptAnyServerCertificateValidator. This bypasses all certificate validation, which is acceptable in local development but must never reach production. In production, trust the certificate in the operating system's certificate store or use a properly issued certificate.

The SSL error HttpClient throws

When HttpClient connects to a server whose certificate is untrusted (self-signed, expired, wrong hostname, or issued by an unknown CA), it throws:

csharp
1using var client = new HttpClient();
2var response = await client.GetAsync("https://localhost:5001/api/data");
3// System.Net.Http.HttpRequestException:
4//   The SSL connection could not be established, see inner exception.
5// Inner: AuthenticationException:
6//   The remote certificate is invalid according to the validation procedure.

The TLS handshake fails because the server's certificate chain cannot be validated against the system's trusted root store.

Using DangerousAcceptAnyServerCertificateValidator

The fastest way to suppress the error in development:

csharp
1var handler = new HttpClientHandler
2{
3    ServerCertificateCustomValidationCallback =
4        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
5};
6
7using var client = new HttpClient(handler);
8var response = await client.GetAsync("https://localhost:5001/api/data");
9Console.WriteLine(response.StatusCode); // OK

The name is intentionally alarming. This delegate returns true for every certificate regardless of errors, hostname mismatches or expiration.

Accepting only specific certificates

A custom callback can accept only certain certificates, a middle ground between full bypass and full validation:

csharp
1var handler = new HttpClientHandler
2{
3    ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
4    {
5        // No errors means the certificate is fully valid
6        if (errors == System.Net.Security.SslPolicyErrors.None)
7            return true;
8
9        // Accept a known self-signed certificate by thumbprint
10        if (cert?.GetCertHashString() == "A1B2C3D4E5F67890ABCDEF1234567890ABCDEF12")
11            return true;
12
13        // Accept any certificate when connecting to localhost
14        if (request.RequestUri?.Host == "localhost")
15            return true;
16
17        // Reject everything else
18        return false;
19    }
20};
21
22using var client = new HttpClient(handler);

The callback receives four parameters:

ParameterTypeDescription
requestHttpRequestMessageThe outgoing HTTP request
certX509Certificate2The server's certificate
chainX509ChainThe full certificate chain
errorsSslPolicyErrorsFlags indicating what validation failed

The relevant SslPolicyErrors values:

ValueMeaning
NoneCertificate is fully valid
RemoteCertificateChainErrorsChain validation failed (self-signed, unknown CA, expired)
RemoteCertificateNameMismatchCertificate hostname does not match the request URL

If you pin a thumbprint, deploying a new certificate requires a code change and redeployment. Plan for rotation by pinning the public key (SPKI) or the issuer instead.

Configuring the bypass with IHttpClientFactory in ASP.NET Core

In ASP.NET Core, do not create HttpClient instances directly. Use IHttpClientFactory to manage handler lifetimes and configure SSL behavior per named or typed client:

csharp
1// Program.cs
2builder.Services.AddHttpClient("DevApi", client =>
3{
4    client.BaseAddress = new Uri("https://localhost:5001");
5})
6.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
7{
8    ServerCertificateCustomValidationCallback =
9        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
10});

Then inject and use the factory:

csharp
1public class OrderService
2{
3    private readonly IHttpClientFactory _httpClientFactory;
4
5    public OrderService(IHttpClientFactory httpClientFactory)
6    {
7        _httpClientFactory = httpClientFactory;
8    }
9
10    public async Task<string> GetOrdersAsync()
11    {
12        var client = _httpClientFactory.CreateClient("DevApi");
13        var response = await client.GetAsync("/api/orders");
14        return await response.Content.ReadAsStringAsync();
15    }
16}

This keeps the bypass scoped to one named client instead of all HTTP traffic in the application. Note that ConfigurePrimaryHttpMessageHandler runs when a new handler is created, and handlers are pooled for two minutes by default, so changing configuration at runtime does not immediately affect pooled handlers.

Enabling the bypass only in development

Gate the bypass on the hosting environment or a configuration flag:

csharp
1// Option 1: Check the hosting environment
2var isDevelopment = builder.Environment.IsDevelopment();
3
4builder.Services.AddHttpClient("ApiClient")
5    .ConfigurePrimaryHttpMessageHandler(() =>
6    {
7        // The factory needs a new handler instance on every call
8        var handler = new HttpClientHandler();
9        if (isDevelopment)
10        {
11            handler.ServerCertificateCustomValidationCallback =
12                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
13        }
14        return handler;
15    });
csharp
1// Option 2: Use a configuration flag
2var bypassSsl = builder.Configuration.GetValue<bool>("BypassSslValidation");
3
4builder.Services.AddHttpClient("ApiClient")
5    .ConfigurePrimaryHttpMessageHandler(() =>
6    {
7        var handler = new HttpClientHandler();
8        if (bypassSsl)
9        {
10            handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
11        }
12        return handler;
13    });

With Option 2, set BypassSslValidation in appsettings.Development.json but not in appsettings.Production.json.

Shipping the bypass to production is the one thing you must not get wrong. It exposes every request to man-in-the-middle attacks: anyone on the network can intercept, read and modify the traffic. A singleton HttpClient registered with the bypass is especially risky, since a misconfiguration leaves every request unprotected for the whole process lifetime.

The proper fix: trust the certificate

Add the certificate to the trusted store so HttpClient validates it normally:

bash
1# Windows: import to the Trusted Root Certification Authorities store
2certutil -addstore -f "ROOT" my-dev-cert.crt
3
4# macOS: add to the System keychain
5sudo security add-trusted-cert -d -r trustRoot \
6  -k /Library/Keychains/System.keychain my-dev-cert.crt
7
8# Linux (Debian/Ubuntu): add to system certificates
9sudo cp my-dev-cert.crt /usr/local/share/ca-certificates/
10sudo update-ca-certificates
11
12# Linux (RHEL/CentOS): use the trust command
13sudo cp my-dev-cert.crt /etc/pki/ca-trust/source/anchors/
14sudo update-ca-trust
15
16# ASP.NET Core development certificate
17dotnet dev-certs https --trust

After that, HttpClient accepts the certificate with no custom callback. Use this approach in staging and production.

For Docker images built from minimal base images, which often lack the host's trusted certificates, copy the CA certificate into the image during the build (COPY ca.crt /usr/local/share/ca-certificates/ followed by RUN update-ca-certificates) instead of bypassing validation in code.

.NET Framework: ServicePointManager

In .NET Framework (not .NET Core/.NET 5+), SSL validation is controlled globally through ServicePointManager:

csharp
// .NET Framework only: affects ALL HTTP connections in the entire process
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, errors) => true;

This is more dangerous than the per-handler approach because it disables validation for every HttpClient, WebClient and HttpWebRequest in the process, including those created by third-party libraries. It does not work in .NET Core; there, the per-handler ServerCertificateCustomValidationCallback is the only option, and it is safer because it is scoped to one client.

Comparing the approaches

ApproachScope.NET VersionRisk Level
HttpClientHandler callbackSingle client.NET Core+Moderate (scoped)
IHttpClientFactory handler configNamed/typed client.NET Core+Moderate (scoped)
ServicePointManager callbackEntire process.NET FrameworkHigh (global)
Trust certificate in OS storeSystem-wideAnyLow (proper fix)
dotnet dev-certs https --trustDev machine.NET Core+Low (dev only)

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design