Last active
June 12, 2024 08:34
-
-
Save johnkors/454c829aa63e7663745da5ebeb38dd86 to your computer and use it in GitHub Desktop.
Fetch an accesstoken from IdentityServer3 using PowerShell 3
This file contains hidden or 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
<# | |
.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