|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Reflection; |
| 4 | +using System.Security.Authentication; |
| 5 | +using System.Security.Cryptography.X509Certificates; |
| 6 | +using System.Text; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace System.Net.Security |
| 11 | +{ |
| 12 | + internal static class SslStreamExtensions |
| 13 | + { |
| 14 | + public static Task AuthenticateAsClientAsync(this SslStream sslStream, SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) |
| 15 | + { |
| 16 | + return Task.Factory.FromAsync( |
| 17 | + BeginAuthenticateAsClient, |
| 18 | + iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar), |
| 19 | + sslClientAuthenticationOptions, cancellationToken, |
| 20 | + sslStream); |
| 21 | + } |
| 22 | + |
| 23 | + public static IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, object asyncState) |
| 24 | + { |
| 25 | + // .NET Standard 2.0 and below |
| 26 | + bool checkCertificateRevocation = (sslClientAuthenticationOptions.CertificateRevocationCheckMode != X509RevocationMode.NoCheck); |
| 27 | + SslProtocols sslProtocols = sslClientAuthenticationOptions.EnabledSslProtocols; |
| 28 | + try |
| 29 | + { |
| 30 | + return ((SslStream)asyncState).BeginAuthenticateAsClient(sslClientAuthenticationOptions.TargetHost, sslClientAuthenticationOptions.ClientCertificates, sslProtocols, checkCertificateRevocation, asyncCallback, asyncState); |
| 31 | + } |
| 32 | + catch (ArgumentException e) when (e.ParamName == "sslProtocolType") |
| 33 | + { |
| 34 | + // .NET Framework prior to 4.7 will throw an exception when SslProtocols.None is provided to BeginAuthenticateAsClient. |
| 35 | + sslProtocols = SecurityProtocol.DefaultSecurityProtocols; |
| 36 | + return ((SslStream)asyncState).BeginAuthenticateAsClient(sslClientAuthenticationOptions.TargetHost, sslClientAuthenticationOptions.ClientCertificates, sslProtocols, checkCertificateRevocation, asyncCallback, asyncState); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments