Invoke-WebRequest Basic authentication credentials using UserName and Password
Today in this article we will learn how to make secured API calls using PowerShell Invoke-WebRequest for Basic authentication credentials in the script with simple easy to understanding examples.
We shall cover below aspects of enabling the Basic Authentication security scheme,
What is Basic Authentication
Basic authentication is an Authentication Scheme built into the HTTP protocol which uses a simple username and password to access a restricted resource.
Basic Authentication scheme transmits credentials like user ID/password encoded using the base64 string.
Command
Authorization: Basic <credentials(base64)>
Authorization: Basic VGVzdDpQYXNzd29yZA===
$token"='xxxxxxxxxxx'
$headers = @{
'Content-Type'='application/json'
'Authorization'= 'Basic $token'
}
Once you add the required secured header, you simply call API using the below way,
Constructing Base64 string token in Powershell
If you have UserName and Password for example “Test“, “Password” then the Base64 string token should be as below,
One can construct a base64 string (above used as token ) as below
Call API with Basic Authentication in Powershell using Invoke-WebRequest
Once you have your headers ready, you can simply call a method invoke-webrequest post,
Example
Invoke-WebRequest -Method 'Post' -Uri $url -Body ($body|ConvertTo-Json) -Headers $headers.
A similar technique can also be used for other Authentication like JWT, OAuth2, etc using Powershell.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.