ps/Modules/Alkami.PowerShell.Choco/Public/Get-BasicAuthHeader.ps1
2023-05-30 22:51:22 -07:00

54 lines
1.6 KiB
PowerShell

function Get-BasicAuthHeader {
<#
.SYNOPSIS
Turns a PSCredential into a basic auth header for usage with Invoke-WebRequest
.DESCRIPTION
Turns a PSCredential into a basic auth header for usage with Invoke-WebRequest
When given a credential object, returns an object with a property Authorization and value set accordingly
When given no credential object, returns a $null value
.PARAMETER Credential
[PSCredential] Optional parameter - When omitted will return a null string.
.EXAMPLE
Get-BasicAuthHeader
> Get-BasicAuthHeader
< $null
.EXAMPLE
Get-BasicAuthHeader -Credential $credential
> $credential = (Get-AlkamiCredential "test" "test")
> Get-BasicAuthHeader $credential
< @{ Authorization = "Basic dGVzdDp0ZXN0" }
#>
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
Param(
[Parameter(Mandatory=$false)]
[PSCredential]$Credential = $null
)
$loglead = (Get-LogLeadName)
if($null -eq $Credential) {
Write-Verbose "$loglead : No credential specified. Returning empty object."
return @{}
}
Write-Verbose "$loglead : Credential specified. Building basic authentication header for user $($Credential.UserName)"
## Encode credentials into a basic auth header. "$($user):$($pass)";
## Basic Authorization header are base64 encoded credential pairs
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(
("{0}:{1}" -f $Credential.UserName, (Get-PasswordFromCredential $Credential))
))
$basicAuthValue = "Basic $encodedCreds"
$header = @{
Authorization = $basicAuthValue
}
return $header
}