Allow invalid CosmosDB Emulator certificate with DocumentClient
We have a project which is using the older DocumentClient based CosmosDB SDK. Getting this project to communicate with a Docker hosted CosmosDB emulator turned out to be a hassle.
The new SDK contains the following functionality for ignoring certificate issues:
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
HttpClientFactory = () =>
{
HttpMessageHandler httpMessageHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
return new HttpClient(httpMessageHandler);
},
ConnectionMode = ConnectionMode.Gateway
};
CosmosClient client = new CosmosClient(endpoint, authKey, cosmosClientOptions);But the DocumentClient works little differently. But the good thing is that we can pass in a HttpClientHandler when creating the DocumentClient. So to ignore the cert issues when developing locally, one can use:
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
client = new DocumentClient(
new Uri(endPointUrl),
primaryKey,
handler, connectionPolicy
);If you need to configure serializer settings and the http client handler, things are a bit harder as there is not suitable public constructor in DocumentClient for configuring both. Reflection to rescue:
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
client = new DocumentClient(
new Uri(endPointUrl),
primaryKey,
handler, connectionPolicy
);
var prop = client.GetType().GetField("serializerSettings", System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance);
prop.SetValue(client, serializerSettings);