Skip to content

Instantly share code, notes, and snippets.

@turing85
Last active July 8, 2023 12:10
Show Gist options
  • Save turing85/fc66bff1d46c436e721dc37c458da176 to your computer and use it in GitHub Desktop.
Save turing85/fc66bff1d46c436e721dc37c458da176 to your computer and use it in GitHub Desktop.
Get and decode access token from token endpoint
#!/usr/bin/env bash
set -e
shopt -s inherit_errexit
function die() {
if [[ -n "${1}" ]]
then
>&2 echo "${1}"
fi
exit "${2:-1}"
}
function extract_or_die() {
[[ -n "${1}" ]] || die "${2}" "${3:-64}"
echo "${1}"
}
function add_padding() {
local input
read -r input
input=$(extract_or_die "${input}" "argument must be the string to add padding to" "1")
local len="${#input}"
local output
case "$((${len} % 4))" in
2)
output="${input}=="
;;
3)
output="${input}="
;;
*)
output="${input}"
esac
echo "${output}"
}
function get_token() {
local token_endpoint
token_endpoint=$(extract_or_die "${1}" "1st parameter must be the token endpoint")
local client_id
client_id=$(extract_or_die "${2}" "2nd parameter must be client_id")
local client_secret
client_secret=$(extract_or_die "${3}" "3rd parameter must be client_secret")
local username
username=$(extract_or_die "${4}" "4th parameter must be username")
local password
password=$(extract_or_die "${5}" "5th parameter must be password")
echo -n "$(curl \
--data "client_id=${client_id}" \
--data "client_secret=${client_secret}" \
--data "username=${username}" \
--data "password=${password}" \
--data "grant_type=password" \
--silent \
"${token_endpoint}" `# get token from token endpoint` \
| jq ".access_token" `# extract access token from response` \
| sed 's/"\(.*\)"/\1/g' `# remove quotes from access token` \
| sed 's/.*\.\(.*\)\..*/\1/g' `# from the access token, extract the payload` \
| add_padding `# add padding if necesary` \
| base64 --decode `# decode the payload` \
| jq . `# use jq to print it nicely` \
)"
}
if [[ "${1}" == "--help" ]]
then
echo "Usage: get_and_decode_access_token.sh <token-endpoint> <client-id> <client-secret> <username> <password>"
exit 0
fi
get_token "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment