Skip to content

Instantly share code, notes, and snippets.

@ErisDS
Last active June 15, 2023 01:13
Show Gist options
  • Save ErisDS/6334f0e70ec7390ec08530d5ef9bd0d5 to your computer and use it in GitHub Desktop.
Save ErisDS/6334f0e70ec7390ec08530d5ef9bd0d5 to your computer and use it in GitHub Desktop.
Bash Example of Ghost JWT Auth

Demo of generating a JWT and authenticating with Ghost's Admin API.

Usage:

  • Save ghost-auth.sh locally
  • With Ghost running on localhost:2368
  • sh ghost-auth.sh {admin api key} to run

Gotchas:

Bash designed for running on mac os - linux/unix users may need to change line 21 to:

printf '%s' "${input}" | base64 -w0 | tr -d '=' | tr '+' '-' | tr '/' '_'

Designed to authenticate with a local install, change the last line if your Ghost install is elsewhere

#!/usr/bin/env bash
# Read key from script arguments
KEY=${1:-$(</dev/stdin)}
# Split the key into ID and SECRET
TMPIFS=$IFS
IFS=':' read ID SECRET <<< "$KEY"
IFS=$TMPIFS
# Prepare header and payload
NOW=$(date +'%s')
FIVE_MINS=$(($NOW + 300))
HEADER="{\"alg\": \"HS256\",\"typ\": \"JWT\", \"kid\": \"$ID\"}"
PAYLOAD="{\"iat\":$NOW,\"exp\":$FIVE_MINS,\"aud\": \"/v2/admin/\"}"
# Helper function for perfoming base64 URL encoding
base64_url_encode() {
declare input=${1:-$(</dev/stdin)}
# Use `tr` to URL encode the output from base64.
printf '%s' "${input}" | base64 | tr -d '=' | tr '+' '-' | tr '/' '_'
}
# Prepare the token body
header_base64=$(base64_url_encode "$HEADER")
payload_base64=$(base64_url_encode "$PAYLOAD")
header_payload="${header_base64}.${payload_base64}"
# Create the signature
signature=$(printf '%s' "${header_payload}" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$SECRET | base64_url_encode)
# Finally, a JWT token
TOKEN="${header_payload}.${signature}"
curl -H "Authorization: Ghost $TOKEN" "http://localhost:2368/ghost/api/v2/admin/posts/?limit=1"
@joshsizer
Copy link

@ErisDS Is this functionality built into ghost?

I should be able to call a ghost api endpoint with my admin key and have this JWT value returned

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment