Created
July 11, 2020 08:01
-
-
Save asleire/73fda6b5e80ae4c85b2794470fb46257 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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