Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active January 27, 2023 23:11
Show Gist options
  • Save steviecoaster/89cbfbb87ce633282c7bab8cf4b3f8c4 to your computer and use it in GitHub Desktop.
Save steviecoaster/89cbfbb87ce633282c7bab8cf4b3f8c4 to your computer and use it in GitHub Desktop.
Encodes a PSCredential for use against an API using Basic authentication
function New-EncodedCredential {
<#
.SYNOPSIS
Return an base64 encoded credential for use against API authentication
.PARAMETER Credential
The PSCredential object to encode
.PARAMETER AsHeader
Returns a header containing the required authorization information for use with the -Header parameter of Invoke-RestMethod
.EXAMPLE
New-EncodedCredential -Credential (Get-Credential)
.EXAMPLE
New-EncodedCredential -Credential $Credential -AsHeader
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[System.Management.Automation.PSCredential]
$Credential,
[Parameter()]
[Switch]
$AsHeader
)
process {
$credPair = "{0}:{1}" -f $Credential.UserName,$Credential.GetNetworkCredential().Password
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($credPair))
if($AsHeader){
@{ Authorization = "Basic $encodedCreds" }
}
else {
return $encodedCreds
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment