Last active
January 27, 2023 23:11
-
-
Save steviecoaster/89cbfbb87ce633282c7bab8cf4b3f8c4 to your computer and use it in GitHub Desktop.
Encodes a PSCredential for use against an API using Basic authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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