Private/New-GhostToken.ps1

function New-GhostToken {
    <#
    .SYNOPSIS
        Creates the short-lived JSON Web Token that authenticates a request to the Ghost Admin API.

    .DESCRIPTION
        An Admin API key has the form <id>:<secret>. The id becomes the kid of the token header and the secret,
        which is hex encoded, signs the token with HMAC SHA-256. Ghost accepts tokens that are valid for at most
        five minutes and have /admin/ as audience.

    .EXAMPLE
        New-GhostToken -KeyId $connection.KeyId -Secret $connection.Secret

        Returns a token that is valid for five minutes.

    .LINK
        https://docs.ghost.org/admin-api#token-authentication
    #>

    [CmdletBinding()]
    [OutputType([string])]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        'PSUseShouldProcessForStateChangingFunctions', '',
        Justification = 'Builds a token in memory. Nothing is changed on the system or on the site.'
    )]
    param(
        # The id part of the Admin API key.
        [Parameter(Mandatory)]
        [ValidatePattern('^[0-9a-fA-F]+$')]
        [string] $KeyId,

        # The secret part of the Admin API key: an even number of hexadecimal characters.
        [Parameter(Mandatory)]
        [securestring] $Secret,

        # Number of seconds the token is valid. Ghost rejects more than 300.
        [ValidateRange(1, 300)]
        [int] $LifetimeSeconds = 300,

        # The moment the token is issued. Defaults to now.
        [datetimeoffset] $IssuedAt = [datetimeoffset]::UtcNow
    )

    $hex = [System.Net.NetworkCredential]::new('', $Secret).Password
    if ($hex -notmatch '^(?:[0-9a-fA-F]{2})+$') {
        throw 'The secret of the Admin API key must be an even number of hexadecimal characters.'
    }

    # The JSON is written out by hand: both objects are tiny and this keeps the output identical on every
    # PowerShell version. The key id is validated as hexadecimal, so it needs no escaping.
    $issued = $IssuedAt.ToUnixTimeSeconds()
    $header = '{{"alg":"HS256","typ":"JWT","kid":"{0}"}}' -f $KeyId
    $payload = '{{"iat":{0},"exp":{1},"aud":"/admin/"}}' -f $issued, ($issued + $LifetimeSeconds)
    $unsigned = '{0}.{1}' -f @(
        ConvertTo-Base64Url -Bytes ([System.Text.Encoding]::UTF8.GetBytes($header))
        ConvertTo-Base64Url -Bytes ([System.Text.Encoding]::UTF8.GetBytes($payload))
    )

    # The key is the decoded secret, not the hexadecimal text.
    $key = [byte[]]::new($hex.Length / 2)
    for ($index = 0; $index -lt $key.Length; $index++) {
        $key[$index] = [System.Convert]::ToByte($hex.Substring($index * 2, 2), 16)
    }

    $hmac = [System.Security.Cryptography.HMACSHA256]::new($key)
    try {
        $signature = ConvertTo-Base64Url -Bytes $hmac.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($unsigned))
    }
    finally {
        $hmac.Dispose()
        [System.Array]::Clear($key, 0, $key.Length)
    }

    '{0}.{1}' -f $unsigned, $signature
}