zXynK
zXynK

Reputation: 1332

Cosmos with EFCore - can we bypass the SSL check?

Similar question to How to bypass SSL and access cosmosDb emulator from docker container running a .net core app?

I'm using EFCore 5 at the moment. I don't know if this is fixed in 6 but I'm hoping to avoid upgrading at this point.

This is what I have at the moment:

options.UseCosmos(
    accountEndpoint: settings.Uri,
    accountKey: settings.Key,
    databaseName: settings.DatabaseName,
    (clientOptions) => new CosmosClientOptions()
    {
        ConnectionMode = ConnectionMode.Gateway,
        HttpClientFactory = () =>
            new HttpClient(new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            })
    });

I'm expecting to be able to use Cosmos Emulator running in Docker:

docker-compose.yml
version: '3.9'
services:
  cosmos:
    container_name: core.cosmos
    image: mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
    restart: always
    ports:
      - "8081:8081"
    environment:
      - AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10

When calling context.Database.EnsureCreated();, I get the following exception:

System.Net.Http.HttpRequestException: 'The SSL connection could not be established, see inner exception.'
Inner Exception:
AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

I've put a breakpoint inside ServerCertificateCustomValidationCallback which is never hit, which means it's ignored or never actually set.

I've inspected context.Database.GetCosmosClient() and it appears HttpClientFactory is null, but even if I try to set it there before calling EnsureCreated, I still get the exception.

Upvotes: 0

Views: 1387

Answers (1)

ragnar
ragnar

Reputation: 190

Apparently, creating a new object CosmosClientOptions does not work. I fixed my issue by mutating the existing object

Example:

(clientOptions) => {
                     clientOptions.HttpClientFactory( () => {
                         HttpMessageHandler httpMessageHandler = new HttpClientHandler()
                            {
                                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                            };

                        return new HttpClient(httpMessageHandler);
                     });
                     clientOptions.ConnectionMode(ConnectionMode.Gateway);
                 });

Upvotes: 1

Related Questions