Skip to content

Instantly share code, notes, and snippets.

@nickfloyd
Created June 25, 2011 14:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nickfloyd/1046526 to your computer and use it in GitHub Desktop.
Save nickfloyd/1046526 to your computer and use it in GitHub Desktop.
Powershell basic authentication
//This returns a 404 not found - powershell; I expected a 401 if my creds were bad
$Url = "https://github.com/api/v2/xml/commits/list/fellowshiptech/portal/Portal_2011.6.23_15-26"
$webclient = new-object system.net.webclient
$webclient.credentials = new-object system.net.networkcredential("user", "password")
$result = $webclient.DownloadString($Url)
$result
//This returns the data I want via terminal
curl -u user:password https://github.com/api/v2/xml/commits/list/fellowshiptech/portal/Portal_2011.6.23_15-26
//Here's how to do it via powershell - though I am not a fan of the implementation
$webclient = new-object system.net.webclient
$result = $webclient.DownloadString("https://github.com/api/v2/xml/commits/list/fellowshiptech/portal/Portal_2011.6.23_15-26?login=:user&token=:token")
$result
@RMcD
Copy link

RMcD commented Feb 5, 2013

Might try: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.preauthenticate.aspx

$webrequest = [System.Net.WebRequest]::Create("$uriBase$urlSuffix")
Write-Host $webrequest.RequestUri
$webrequest.PreAuthenticate = $true
#Add useragent header if needed
#$webrequest.Headers.Add("UserAgent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/535.2")
$webrequest.Credentials = new-object system.net.networkcredential("user", "password")
$response = $webrequest.GetResponse()
$sr = [Io.StreamReader]($response.GetResponseStream()) 
[xml]$xmlout = $sr.ReadToEnd()

Also in Powershell 3 there is the Invoke-RestMethod cmdlet that makes the whole process much simpler
http://go.microsoft.com/fwlink/?LinkID=217034

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment