Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to login to website with basic authentication using Powershell

Tags:

powershell

I am trying to use PowerShell to log into a website and download a file.

However I can't get PS to pass the credentials properly.

Here is my PS:

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential("username","password","domain")
$webpage = $webclient.DownloadString("url goes here")

Here is the log in box I get when I hit the site in IE: enter image description here

like image 207
Clarence Klopfstein Avatar asked Sep 05 '12 13:09

Clarence Klopfstein


People also ask

How can I pass the basic HTTP authentication?

We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.

How do I pass credentials in PowerShell without prompt?

$cred = Get-Credential without asking for prompts in powershell.


2 Answers

This is what I got to work. I believe the key part is the "Basic" in the CredentialCache

$webclient = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential("un","pw")
$credCache.Add("url", "Basic", $creds)
$webclient.Credentials = $credCache
$webpage = $webclient.DownloadString("url")
like image 75
Clarence Klopfstein Avatar answered Oct 03 '22 07:10

Clarence Klopfstein


If you want to use Invoke-WebRequest instead of the WebClient:

$securepassword = ConvertTo-SecureString "password" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential("username", $securepassword)
Invoke-WebRequest -Uri "url goes here" -Credential $credentials

I based the code on this blog article by Douglas Tarr. Note that in the article the username and password are confused, but I've fixed them in my sample.

like image 21
Aaron D Avatar answered Oct 03 '22 08:10

Aaron D