'connect to a server with a self-signed certificate

Ive been doing some research about how to consume a web api executed on my localhost throught a xamarin app. The web api works perfect, I can adding and getting the data to/from my sql server using a web browser but if I try to connect xamarin to it Ive always received authentication error (Mono.Btls.MonoBtlsException: Ssl error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED). Im basically doind this. I followed this post:

http://xamarininterviewquestion.blogspot.com/2019/06/ssl-certificate-and-public-key-pinning.html

So as it definitly didnt work, Id like to try another way;

Set TLSConfig DangerousAcceptAnyServerCertificateValidator to true. Because for know Im happy if Im able to test it.

Thats cool but as Im not a pro I have no idea about implement this;

var httpHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpHandler.ServerCertificateCustomValidationCallback = 
    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

Ive got "DangerousAcceptAnyServerCertificateValidator" doesnt have a definition.

Thank you all in advance and sorry if Ive not been clear.



Solution 1:[1]

DangerousAcceptAnyServerCertificateValidator isn't applicable to Xamarin platforms, according to its documentation.

But literally you can write the same code like,

var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpClient client = new HttpClient(handler);

https://stackoverflow.com/a/64741829/11182

Solution 2:[2]

if you are using Refit then you can do this

public HttpClient PreparedClient()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; };
            HttpClient client = new HttpClient(handler) { BaseAddress = new Uri(EndpointConstants.BaseUrl) };
            return client;
        }

 private T RefitApi<T>() => RestService.For<T>(PreparedClient());

and if you need to specify settings you can do this

 private T RefitApiWithToken<T>() => RestService.For<T>(PreparedClient(), refitSettings);

Solution 3:[3]

When using Refit for Xamarin forms

public HttpClient PreparedClient()
    {
        HttpClientHandler handler = new HttpClientHandler();
        handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; };
        HttpClient client = new HttpClient(handler) { BaseAddress = new Uri(EndpointConstants.BaseUrl) };
        return client;
    }
var apiResponse = RestService.For<T>(PreparedClient());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lex Li
Solution 2 Ronak Shethia
Solution 3 abubakar ahmed