Created
November 18, 2021 14:30
-
-
Save OriBenHur/4ce42b6cbd7db6d4098357e563caaec4 to your computer and use it in GitHub Desktop.
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 | |
function get_access_token(){ | |
set -euo pipefail | |
local key_json_file="${1}" | |
local scope="${2}" | |
local valid_for_sec="${3:-3600}" | |
local jwt_token | |
jwt_token=$(create_jwt_token "${key_json_file}" "${scope}" "${valid_for_sec}") | |
curl -s -X POST https://www.googleapis.com/oauth2/v4/token \ | |
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer' \ | |
--data-urlencode "assertion=${jwt_token}" \ | |
| jq -r .access_token | |
} | |
function create_jwt_token(){ | |
set -euo pipefail | |
local key_json_file="${1}" | |
local scope="${2}" | |
local valid_for_sec="${3:-3600}" | |
local private_key sa_email header claim request_body signature | |
private_key=$(jq -r .private_key "${key_json_file}") | |
sa_email=$(jq -r .client_email "${key_json_file}") | |
header='{"alg":"RS256","typ":"JWT"}' | |
claim=$(jq -c . <<- EOM | |
{ | |
"iss": "$sa_email", | |
"scope": "$scope", | |
"aud": "https://www.googleapis.com/oauth2/v4/token", | |
"exp": $(($(date +%s) + valid_for_sec)), | |
"iat": $(date +%s) | |
} | |
EOM | |
) | |
request_body="$(base64var "${header}").$(base64var "${claim}")" | |
signature=$(openssl dgst -sha256 -sign <(echo "${private_key}") <(printf "${request_body}") | base64stream) | |
printf "%s.%s" "${request_body}" "${signature}" | |
} | |
base64var() { | |
set -euo pipefail | |
echo "${1}" | base64stream | |
} | |
base64stream() { | |
set -euo pipefail | |
base64 | tr '/+' '_-' | tr -d '=\n' | |
} | |
get_access_token "${@}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment