143 votes

Erreur Powershell v3 Invoke-WebRequest HTTPS

En utilisant les méthodes Invoke-WebRequest et Invoke-RestMethod de Powershell v3, j'ai réussi à utiliser la méthode POST pour envoyer un fichier json à un site web https.

La commande que j'utilise est

 $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("cert.crt")
 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Body $json -ContentType application/json -Method POST

Cependant, lorsque j'essaie d'utiliser la méthode GET comme :

 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET

L'erreur suivante est renvoyée

 Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
 At line:8 char:11
 + $output = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred
 +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)      [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

J'ai essayé d'utiliser le code suivant pour ignorer le certificat SSL, mais je ne suis pas sûr qu'il fasse quoi que ce soit.

 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Quelqu'un peut-il fournir des conseils sur ce qui pourrait se passer ici et sur la façon de le réparer ?

Gracias

207voto

Lee Grissom Points 2649

Cette solution de contournement a fonctionné pour moi : http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

En gros, dans votre script PowerShell :

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

89voto

AndOs Points 964

La réponse de Lee est excellente, mais j'ai également eu des problèmes avec les protocoles pris en charge par le serveur web.
Après avoir également ajouté les lignes suivantes, j'ai pu faire passer la requête https. Comme indiqué dans cette réponse https://stackoverflow.com/a/36266735

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

Ma solution complète avec le code de Lee.

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

17voto

TheIncorrigible1 Points 11640

Une mise en œuvre alternative en pure powershell (sans Add-Type de c# source) :

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

10voto

Sunny Chakraborty Points 212

Avez-vous essayé d'utiliser System.Net.WebClient ?

$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)

9voto

Amar Helloween Points 91

Invoke-WebRequest "NomDeDomaine" -SkipCertificateCheck

Vous pouvez utiliser -SkipCertificateCheck Paramètre permettant de réaliser cette opération en une seule ligne de commande ( CE PARAMÈTRE EST UNIQUEMENT SUPPORTÉ PAR CORE PSEDITION )

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X