.net rest powershell https

.net - powershell ajax call



Powershell v3 Invoke-WebRequest Error de HTTPS (8)

Utilizando Invoke-WebRequest y Invoke-RestMethod de Powershell v3 He utilizado con éxito el método POST para publicar un archivo json en un sitio web https.

El comando que estoy usando es

$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

Sin embargo, cuando intento usar el método GET como:

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

El siguiente error es devuelto

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

Intenté usar el siguiente código para ignorar el certificado SSL, pero no estoy seguro de si realmente está haciendo algo.

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

¿Puede alguien proporcionar alguna guía sobre lo que podría estar pasando mal aquí y cómo solucionarlo?

Gracias


  1. Ejecuta este comando

New-SelfSignedCertificate -certstorelocation cert: / localmachine / my -dnsname {your-site-hostname}

en powershell con derechos de administrador , esto generará todos los certificados en el directorio personal

  1. Para eliminar el error de privacidad, seleccione estos certificados, haga clic con el botón derecho → Copiar. Y pegue en Trusted Root Certification Authority / Certificates.
  2. El último paso es seleccionar enlaces correctos en IIS. Vaya al sitio web de IIS, seleccione Vinculaciones, seleccione la casilla de verificación SNI y configure los certificados individuales para cada sitio web.

Asegúrese de que el nombre de host del sitio web y el nombre dns del certificado coincidan exactamente


¿ System.Net.WebClient usar 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)


El siguiente trabajo funcionó para mí (y usa los últimos medios no obsoletos para interactuar con la funcionalidad SSL Certs / callback), y no intenta cargar el mismo código varias veces dentro de la misma sesión de PowerShell:

if (-not ([System.Management.Automation.PSTypeName]''ServerCertificateValidationCallback'').Type) { $certCallback=@" using System; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class ServerCertificateValidationCallback { public static void Ignore() { if(ServicePointManager.ServerCertificateValidationCallback ==null) { ServicePointManager.ServerCertificateValidationCallback += delegate ( Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors ) { return true; }; } } } "@ Add-Type $certCallback } [ServerCertificateValidationCallback]::Ignore();

Esto fue adaptado del siguiente artículo https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/


Encontré que cuando usé la función de devolución de llamada para ignorar los certificados SSL [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Siempre recibí el mensaje de error Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send. que suena como los resultados que estás teniendo.

Encontré esta publicación en el foro que me llevó a la siguiente función. Ejecuto esto una vez dentro del alcance de mi otro código y funciona para mí.

function Ignore-SSLCertificates { $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider $Compiler = $Provider.CreateCompiler() $Params = New-Object System.CodeDom.Compiler.CompilerParameters $Params.GenerateExecutable = $false $Params.GenerateInMemory = $true $Params.IncludeDebugInformation = $false $Params.ReferencedAssemblies.Add("System.DLL") > $null $TASource=@'' namespace Local.ToolkitExtensions.Net.CertificatePolicy { public class TrustAll : System.Net.ICertificatePolicy { public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem) { return true; } } } ''@ $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource) $TAAssembly=$TAResults.CompiledAssembly ## We create an instance of TrustAll and attach it to the ServicePointManager $TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll") [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll }


Este work-around funcionó para mí: http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

Básicamente, en su secuencia de comandos de 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"


Intenté buscar documentación sobre la API REST de EM7 OpenSource. Sin suerte hasta ahora.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

Se habla mucho sobre la API REST de OpenSource, pero no hay un enlace a la API real ni a ninguna documentación. Tal vez estaba impaciente.

Aquí hay algunas cosas que puedes probar

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert $a.Results | ConvertFrom-Json

Intente esto para ver si puede filtrar las columnas que obtiene de la API

$a.Results | ft

o puedes intentar usar esto también

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert $b.Content | ConvertFrom-Json

Encabezados de estilo de curvatura

$b.Headers

Probé el IRM / IWR con la api de Twitter JSON.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell

Espero que esto ayude.


La respuesta de Lee es excelente, pero también tuve problemas con los protocolos compatibles con el servidor web.
Después de agregar también las siguientes líneas, pude obtener la solicitud https a través de. Como se señala en esta respuesta, https://.com/a/36266735

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

Mi solución completa con el código 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


Si ejecuta esto como administrador, ese error debería desaparecer