Powershell Script to create Basic Authentication for REST calls

Lately I have found my self playing with REST APIs more and more, since almost everything these days seems to have one. Much of my testing is first done using Chrome’s Advanced REST Client or Postman before consuming the API in either Powershell, Java, or similar.

I have put together a simple Powershell script for converting Username and Passwords to a Basic Authentication string which can be used in REST calls’ headers. I also include similar code in some of my Powershell scripts that consume REST APIs.

 

 Param(
     [Parameter(Mandatory=$TRUE,Position=1)]
     [string]$username,
     [Parameter(Mandatory=$TRUE)]
     [Security.SecureString]$password
)


$tempPW = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$uPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($tempPW)

$UserAndPass = "${username}:${uPassword}"

$output = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($UserAndPass))}

$output

Some items to note: You don’t have to take the parameters, I use this simply because many of my scripts I share with team members, so each person may be using a different set of credentials, and I prefer to use this method to capture their passwords securely. You could start at the “$output” line and make this a one-liner. Since “$output” is an array this could be used as a REST header itself.

Let me know what you think!

 

Leave a Reply

Your email address will not be published. Required fields are marked *