Jelte
Jelte

Reputation: 207

Powershell download file using basic auth

I'm trying to download a file from my JFrog repo using PowerShell but I can't get it to work.

This is the error I'm getting:

Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error
occurred on a send."
At     C:\Users\jelte\Documents\myproject\downloadExecutables1.ps1:16 char:1
+ $req.DownloadFile('https://myrepo.jfrog.io/myproject/libs-release-loca ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], 

MethodInvocationException

The code I use:

$usernameVar = "JFROG_USERNAME"
$username = (get-item env:$usernameVar).Value

$passwordVar = "JFROG_PASSWORD"
$password = (get-item env:$passwordVar).Value

$auth = 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password))
$req = New-Object System.Net.WebClient
$req.Headers.Add('Authorization', $auth)
$installersFolder = $PSScriptRoot + '\prerequisites\executables'
If(!(test-path $installersFolder))
{
      New-Item -ItemType Directory -Force -Path $installersFolder
}

$req.DownloadFile('https://myrepo.jfrog.io/myproject/libs-release-local/binary/com/targetexecutable/9.3.240/executable-9.3.240.exe', $installersFolder + '\executable-9.3.240.exe')

Things I tried:

  1. Downloading a file from a non-secured server, that works. I suspect that there's something going wrong in the basic authentication.
  2. I have checked if username and password are filled in, I also checked if the base64 hash was correct.
  3. Putting PowerShell in trace mode so I can get more clear errors, no luck. (Why are these errors so unclear?)
  4. Using Invoke-Webrequest, this works but it's extremely slow.
  5. Using cURL to check if it's something else, that also works.

Upvotes: 7

Views: 2118

Answers (2)

dwillits
dwillits

Reputation: 313

I'm with Setorica, it looks familiar to errors I've had in regards to security protocols. Here's a single line solution, just add it to the top of your script.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Upvotes: 2

Setorica
Setorica

Reputation: 472

Try adding these lines to the beginning of your script.

$AllProtocols = [System.Net.SecurityProtocolType]'Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols 

I experienced something similar without a very informative error message and the problem was apparently just that I needed to set the security protocol that powershell uses to Tls 1.2.

Upvotes: 2

Related Questions