Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch an accesstoken from IdentityServer3 using PowerShell 3
<#
.SYNOPSIS
Fetches an access token using the IdentityServer3 token endpoint
.DESCRIPTION
Modify the parameters so it matches your IdentityServer3 instance.
.NOTES
File Name : GetToken.ps1
Author : John Korsnes (@johnkors, johnkors)
Prerequisite : PowerShell V3
.LINK
https://identityserver.github.io/Documentation/docsv2/endpoints/token.html
#>
$identityserverUrl = "https://localhost:44333/core"
$tokenendpointurl = $identityserverUrl + "/connect/token"
$granttype = "client_credentials" # client_credentials / password
$client_id = ""
$client_secret = ""
$username = ""
$password = ""
$scope = ""
function Convert-FromBase64StringWithNoPadding([string]$data)
{
$data = $data.Replace('-', '+').Replace('_', '/')
switch ($data.Length % 4)
{
0 { break }
2 { $data += '==' }
3 { $data += '=' }
default { throw New-Object ArgumentException('data') }
}
return [System.Convert]::FromBase64String($data)
}
function FetchToken
{
$body = @{
grant_type = $granttype
scope = $scope
client_id = $client_id
client_secret = $client_secret
username = $username
password = $password
}
$resp = Invoke-RestMethod -Method Post -Body $body -Uri $tokenendpointurl
$parts = $resp.access_token.Split('.');
$baseDecoded = Convert-FromBase64StringWithNoPadding($parts[1])
$decoded = [System.Text.Encoding]::UTF8.GetString($baseDecoded)
Write-Host "`***** SUCCESSFULLY FETCHED TOKEN ***** `n" -foreground Green
Write-Host "`JWT payload: `n" -foreground Yellow
$decoded = $decoded | ConvertFrom-Json | ConvertTo-Json
Write-Host $decoded -foreground White
Write-Host
Write-Host "`ACCESSTOKEN: `n" -foreground Yellow
Write-Host ($resp.access_token | Format-Table -Wrap | Out-String ) -foreground White
Write-Host
}
cls
try
{
FetchToken
}
catch
{
Write-Host "`***** FETCHING TOKEN EXPERIENCED ERROR ***** `n" -foreground Red
Write-Host $_ -foreground Red
Write-Host
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment