Skip to content

Instantly share code, notes, and snippets.

@asleire
Created July 11, 2020 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asleire/73fda6b5e80ae4c85b2794470fb46257 to your computer and use it in GitHub Desktop.
Save asleire/73fda6b5e80ae4c85b2794470fb46257 to your computer and use it in GitHub Desktop.
/// <summary>
/// Ugly reflection hack to allow unsecure SSL.
/// </summary>
/// <returns></returns>
private CosmosClient CreateNoSslCosmosClient()
{
var db = new CosmosClientBuilder($"https://localhost:{_hostPort}", "dummy key")
.WithConnectionModeGateway()
.WithSerializerOptions(
new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase }
).Build();
var assembly = typeof(CosmosClient).Assembly;
var ctx = typeof(CosmosClient).GetProperty("ClientContext", BindingFlags.Instance | BindingFlags.NonPublic)
!.GetValue(db) ?? throw new InvalidOperationException("Broken reflection");
var docClient = assembly.GetType("Microsoft.Azure.Cosmos.CosmosClientContext")!.GetProperty(
"DocumentClient",
BindingFlags.Instance | BindingFlags.NonPublic
)
!.GetValue(ctx) ?? throw new InvalidOperationException("Broken reflection 2");
var httpMessageHandlerField = docClient.GetType().GetField(
"httpMessageHandler",
BindingFlags.Instance | BindingFlags.NonPublic
);
var httpRequestMessageHandlerType =
docClient.GetType().GetNestedType("HttpRequestMessageHandler", BindingFlags.NonPublic) ??
throw new InvalidOperationException("Broken reflection 3");
var existingHandler = httpMessageHandlerField!.GetValue(docClient)! as HttpMessageHandler;
var existingHandlerSendingRequest = httpRequestMessageHandlerType
.GetField("sendingRequest", BindingFlags.Instance | BindingFlags.NonPublic)
!.GetValue(existingHandler);
var existingHandlerReceivedResponse = httpRequestMessageHandlerType
.GetField("receivedResponse", BindingFlags.Instance | BindingFlags.NonPublic)
!.GetValue(existingHandler);
var httpRequestMessageHandlerCtor = httpRequestMessageHandlerType.GetConstructors().First();
var messageHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
};
var newHandler = httpRequestMessageHandlerCtor.Invoke(
BindingFlags.CreateInstance,
null,
new[]
{
existingHandlerSendingRequest,
existingHandlerReceivedResponse,
messageHandler
},
CultureInfo.InvariantCulture
);
httpMessageHandlerField.SetValue(docClient, newHandler);
return db;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment