Last active
November 15, 2024 15:35
-
-
Save magickatt/22d764446fae5b40b5af981e0b27da4f to your computer and use it in GitHub Desktop.
Generate GitHub App JWT and Token
This file contains 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
#!/usr/bin/env bash | |
# Combination of generating the JWT and the token | |
# https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app#generating-a-json-web-token-jwt | |
# https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app#using-a-json-web-token-jwt-to-authenticate-as-a-github-app | |
# https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app#generating-an-installation-access-token | |
# https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation | |
set -o pipefail | |
client_id=$GITHUB_APP_ID | |
install_id=$GITHUB_INSTALL_ID | |
pem=$GITHUB_APP_PEM | |
now=$(date +%s) | |
iat=$((${now} - 60)) # Issues 60 seconds in the past | |
exp=$((${now} + 600)) # Expires 10 minutes in the future | |
b64enc() { openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n'; } | |
# JWT header | |
header_json='{ | |
"typ":"JWT", | |
"alg":"RS256" | |
}' | |
header=$( echo -n "${header_json}" | b64enc ) | |
payload_json="{ | |
\"iat\":${iat}, | |
\"exp\":${exp}, | |
\"iss\":\"${client_id}\" | |
}" | |
payload=$( echo -n "${payload_json}" | b64enc ) | |
header_payload="${header}"."${payload}" | |
signature=$( | |
openssl dgst -sha256 -sign <(echo -n "${pem}") \ | |
<(echo -n "${header_payload}") | b64enc | |
) | |
# Create JWT | |
JWT="${header_payload}"."${signature}" | |
curl_status=$(curl --request GET --silent --output /dev/null \ | |
--write-out "%{http_code}" \ | |
--url "https://api.github.com/app/installations" \ | |
--header "Accept: application/vnd.github+json" \ | |
--header "Authorization: Bearer $jwt" \ | |
--header "X-GitHub-Api-Version: 2022-11-28") | |
echo "GitHub App JWT API test response code: ${curl_status}" | |
printf '%s\n' "JWT: $jwt" | |
# Create token (requires the JWT) | |
token=$(curl --request POST --silent \ | |
--url "https://api.github.com/app/installations/$install_id/access_tokens" \ | |
--header "Accept: application/vnd.github+json" \ | |
--header "Authorization: Bearer $jwt" \ | |
--header "X-GitHub-Api-Version: 2022-11-28" | jq .token --raw-output) | |
printf '%s\n' "Token: ${token}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment