Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell download file using basic auth

Tags:

powershell

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.
like image 547
Jelte Avatar asked Aug 10 '26 23:08

Jelte


2 Answers

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.

like image 107
Setorica Avatar answered Aug 12 '26 20:08

Setorica


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
like image 24
dwillits Avatar answered Aug 12 '26 21:08

dwillits



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!