#!/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}"