Skip to content

Instantly share code, notes, and snippets.

@rezarahimian
Last active August 25, 2020 21:55
Show Gist options
  • Save rezarahimian/0273c9b5a2d7ad5dd296d3add6bc7777 to your computer and use it in GitHub Desktop.
Save rezarahimian/0273c9b5a2d7ad5dd296d3add6bc7777 to your computer and use it in GitHub Desktop.
[CmdletBinding()]
PARAM(
[Parameter(Mandatory=$true)][String] $CredentialPath,
[Parameter(Mandatory=$true)][String] $Resource
)
try
{
$Token = $null
$Credential = [System.Management.Automation.PSCredential](Import-Clixml -Path $CredentialPath)
$EndPointURL = 'https://sso.private.local/connect/oauth2/token'
Write-Verbose -Message ('Connecting to "{0}"...' -f $EndPointURL)
$UserName = $Credential.UserName
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password))
$CredBase64 = [Convert]::ToBase64String([byte[]]("${UserName}:$Password".ToCharArray()))
Write-Verbose -Message ('Using "{0}" resource to create access token...' -f $Resource)
$Payload = "token_type=password&scope=openid+profile+$($Resource)&username=$($UserName)&password=$($Password)"
Write-Verbose -Message ('Creating access token for "{0}"...' -f $Credential.UserName)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Token = Invoke-RestMethod -Method Post -Uri $EndPointURL -Body $Payload -ContentType 'application/x-www-form-urlencoded' -Headers @{"Authorization"="Basic $CredBase64"} -Verbose
Write-Verbose -Message ('Created access token successfully : {0}' -f ($Token | Out-String))
}
catch
{
Write-Verbose -Message $_.Exception.Message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment