Where to place RemoteCertificateValidationCallback?

后端 未结 3 1458
忘了有多久
忘了有多久 2020-12-20 05:59

I have the same problem as here: How to disable "Security Alert" window in Webbrowser control

I like the answer, but where am I going to place the Se

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 06:49

    For someone looking to do this in powershell, you can use the following. it is important to not do {$true} for the handler as if called often it can result in a out of runspace error.

    $code = @"
    public class SSLHandler
    {
        public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
        {
    
            return new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
        }
        
    }
    "@
    
    Add-Type -TypeDefinition $code
    #disable checks
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()
    #do the request
    try
    {
        invoke-WebRequest -Uri myurl -UseBasicParsing
    } catch {
        # do something
    } finally {
       #enable checks again
       [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
    }
    

    if you still have some servers running powershell v2 you cannot use an anonymous function, this version will work:

    $code = @"
    public class SSLHandler
    {
        private static bool Callback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    
        public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
        {
    
            return new System.Net.Security.RemoteCertificateValidationCallback(Callback);
        }
        
    }
    "@
    

提交回复
热议问题