Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use PowerShell to call HTTP Endpoint using Basic Auth when you already have a Basic Auth token in hand (not username + password). http://en.wikipedia.org/wiki/Basic_access_authentication
## Example explorers hitting a web endpoint with Basic Auth, when you already have a token in hand
$key = "sk_test_mkGsLqEW6SLnZa487HYfJVLf"
$url = "https://api.stripe.com/v1/charges"
# this will work, but the flow in Basic Auth will first ask you for a password to go with the
# value passed in, which serves as the username. You hit enter because the password is null.
# Then the response comes back... BUT - this also involved a round-trip to the server (which
# returns a 401, but also a Response header indicating that is speaks Basic Auth:
# Www-Authenticate: Basic realm="Stripe"
# With this add'l info, we canretry, this time providing a Base64-encoded username as the
# Basic Auth token in a Request header:
# Authorization: Basic c2tfdGVzdF9ta0dzTHFFVzZTTG5aYTQ4N0hZZkpWTGY6
#
$response = Invoke-WebRequest -Uri $url -Credential $key
$response.Content
$response.Headers
# Alternatively, set up the Basic Auth header up front - if we have a priori knowledge
$authVal = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($key))
$response = Invoke-WebRequest -Uri $url -Headers @{"AUTHORIZATION"=$authVal}
$response.Content
# Or access .Content w/o using a separate variable if you like:
( Invoke-WebRequest -Uri $url -Headers @{"AUTHORIZATION"=$authVal} ).Content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment