Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core HttpClient - "A security error occurred" HttpRequestException

Using .NET Core and C# I'm trying to make an HTTPS request to my Vizio TV, the API is somewhat documented here.

When visiting the HTTP server in Chrome I receive a "NET::ERR_CERT_AUTHORITY_INVALID" error. When I make the request in C# with a HttpClient, a HttpRequestException is thrown. I've tried adding the certificate to Windows but I'm just not familiar enough with TLS.

I'm also not concerned about my communications being snooped on so I would like to just ignore any HTTPS errors.

Here's the relevant code I'm working with.

public async Task Pair(string deviceName) {
    using (var httpClient = new HttpClient())
    try {
        httpClient.BaseAddress = new Uri($"https://{televisionIPAddress}:9000/");

        // Assume all certificates are valid?
        ServicePointManager.ServerCertificateValidationCallback =
            (sender, certificate, chain, sslPolicyErrors) => true;

        deviceID = Guid.NewGuid().ToString();

        var startPairingRequest = new HttpRequestMessage(HttpMethod.Put, "/pairing/start");
        startPairingRequest.Content = CreateStringContent(new PairingStartRequestBody {
            DeviceID = deviceID,
            DeviceName = deviceName
        });

        var startPairingResponse = await httpClient.SendAsync(startPairingRequest); // HttpRequestException thrown here
        Console.WriteLine(startPairingResponse);
    } catch (HttpRequestException e) {
        Console.WriteLine(e.InnerException.Message); // prints "A security error occurred"
    }
}

StringContent CreateStringContent(object obj) {
    return new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
}
like image 928
Austin Cummings Avatar asked Jan 28 '23 11:01

Austin Cummings


1 Answers

Resolved the issue by setting up a HttpClientHandler and setting ServerCertificateCustomValidationCallback to return true.

using (var handler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
})
using (var httpClient = new HttpClient(handler))
like image 153
Austin Cummings Avatar answered Feb 03 '23 07:02

Austin Cummings