Skip to content

Instantly share code, notes, and snippets.

@shayaantx
Last active September 15, 2023 14:11
Show Gist options
  • Save shayaantx/e8c10117fe1674e630a892608ac50bf2 to your computer and use it in GitHub Desktop.
Save shayaantx/e8c10117fe1674e630a892608ac50bf2 to your computer and use it in GitHub Desktop.
generate-github-access-token.sh (for github apps with private keys)
#!/bin/bash
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <APP_ID> <OWNER_REPO_NAME> <PRIVATE_KEY_PATH>"
exit 1
fi
APP_ID="$1"
OWNER_REPO_NAME="$2"
PRIVATE_KEY_PATH="$3"
if [ ! -f "$PRIVATE_KEY_PATH" ]; then
echo "Private key file not found: $PRIVATE_KEY_PATH"
exit 1
fi
HEADER='{"alg":"RS256","typ":"JWT"}'
CURRENT_TIME=$(date +%s)
EXPIRATION_TIME=$((CURRENT_TIME + 60)) # Set the expiration to 60 seconds from now
CLAIM="{\"iat\":$CURRENT_TIME,\"exp\":$EXPIRATION_TIME,\"iss\":\"$APP_ID\"}"
ENCODED_HEADER=$(echo -n "$HEADER" | base64 | tr -d '\n')
ENCODED_CLAIM=$(echo -n "$CLAIM" | base64 | tr -d '\n')
JWT_PAYLOAD="${ENCODED_HEADER}.${ENCODED_CLAIM}"
SIGNATURE=$(echo -n "$JWT_PAYLOAD" | openssl dgst -sha256 -sign "$PRIVATE_KEY_PATH" | base64 | tr -d '\n')
JWT="${JWT_PAYLOAD}.${SIGNATURE}"
# For debugging
#echo "JWT = $JWT"
# Get the installation ID
INSTALLATION_ID=$(curl --silent \
--url https://api.github.com/repos/$OWNER_REPO_NAME/installation \
--header "Accept: application/vnd.github+json" \
--header "Authorization: Bearer $JWT" \
--header "X-GitHub-Api-Version: 2022-11-28" | jq ".id")
# For debugging
#echo "Installation_id = $INSTALLATION_ID"
# Get the access token
GITHUB_APP_ACCESS_TOKEN=$(curl --silent -X POST \
--url https://api.github.com/app/installations/$INSTALLATION_ID/access_tokens \
--header "Accept: application/vnd.github+json" \
--header "Authorization: Bearer $JWT" \
--header "X-GitHub-Api-Version: 2022-11-28" | jq ".token")
GITHUB_APP_ACCESS_TOKEN="${GITHUB_APP_ACCESS_TOKEN//\"/}"
# For debugging
#echo "Github token: ${GITHUB_APP_ACCESS_TOKEN:0:10}...${GITHUB_APP_ACCESS_TOKEN: -5}"
echo $GITHUB_APP_ACCESS_TOKEN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment