.NET exposes access to all java and android API’s so we can use them in our platform specific code.
I have implemented the choose certificate dialog when the user visits a website which requires certificate auth, getting the certificate chosen alias and then using the same to get certificate and private key instance.
There is a class AndroidMessageHandler that inherits HttpMessageHandler, which can be then used to configure HttpsClient (.NET class for Network Request/ to be discussed later)
I have added a custom class which extends AndroidMessageHandler https://learn.microsoft.com/en-us/dotnet/api/xamarin.android.net.androidmessagehandler?cid=kerryherger&view=xamarin-android-sdk-13 and added SSL handling code (using the certificate chosen by the user).
Common Code (used and accessible by the whole app):
I have used the HttpsClient class
Following code snippet shows the use of HttpsClient with custom handler I created and how I configured SSL. This would mean we do not need custom Network Requests implementation for each platform. Instead we need custom handler implementation but the HttpsClient remains the same for requests,
irrespective of the platform.
private SSLContext GetSSLContext() { string protocol; if (SslProtocols == SslProtocols.Tls11) { protocol = "TLSv1.1"; } else if (SslProtocols == SslProtocols.Tls || SslProtocols == SslProtocols.Tls12) { protocol = "TLSv1.2"; } else { throw new IOException("unsupported ssl protocol: " + SslProtocols.ToString()); } IKeyManager keyManager; # KeyChainKeyManager is a custom class keyManager = KeyChainKeyManager.fromAlias(Application.Context, mAlias); SSLContext ctx = SSLContext.GetInstance("TLS"); ctx.Init(new IKeyManager[] { keyManager }, null, null); return ctx; } protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection) { SSLSocketFactory socketFactory = sslContext.SocketFactory; if (connection != null) { connection.SSLSocketFactory = socketFactory; } return socketFactory; }
if ANDROID
new Thread(async () =>
{
# ICertificationService is an interface and implemented in a class CertificationService.
# DependencyService is a way to invoke native platform functionality from shared code.
ICertificationService certificationService = DependencyService.Get<ICertificationService>();
var httpClient = new HttpClient(certificationService.GetAuthAndroidClientHander());
}).Start();
#endif