Skip to content

Instantly share code, notes, and snippets.

@jirutka
Last active July 25, 2023 18:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jirutka/781ef583ac7cdbbbd31d to your computer and use it in GitHub Desktop.
Save jirutka/781ef583ac7cdbbbd31d to your computer and use it in GitHub Desktop.
#!/bin/bash
# vim: tabstop=4
GRANT_TYPE='client_credentials'
############### Functions ###############
parse_json() {
local input=$1
local attr=$2
python -c "import json;obj=json.loads('$input');print(obj['$attr'])" 2>/dev/null
}
############### Arguments ###############
usage() {
cat <<-EOF
Damn simple cript to requests access token from OAuth 2.0 authorization server.
Usage: ${scriptname} <options>
Options:
-c, --client-id CLIENT_ID
-p, --client-secret SECRET
-s, --scope SCOPE...
-u, --oaas-uri URI
-v, --verbose
-h, --help
EOF
}
scriptname=$(basename $0)
client=
secret=
scope=()
oaas_uri='https://auth.fit.cvut.cz'
verbosity='silent'
while [ $# -gt 0 ]; do
case $1
in
-c | --client-id)
client=$2
shift 2
;;
-h | --help)
usage
exit 0
;;
-p | --client-secret)
secret=$2
shift 2
;;
-s | --scope)
scope+=("$2")
shift 2
;;
-u | --oaas-uri)
oaas_uri=$2
shift 2
;;
-v | --verbose)
verbosity='verbose'
shift 1
;;
*)
echo "${scriptname}: Unknown option $1" >&2
echo; usage
exit 1
;;
esac
done
if [[ -z "$client" || -z "$secret" ]]; then
echo "${scriptname}: Missing CLIENT_ID or SECRET" >&2
echo; usage
exit 1
fi
############### Main ###############
data="grant_type=${GRANT_TYPE}"
if [ -n "$scope" ]; then
data+="&scope=${scope[@]}"
fi
curl_opts="
--data "$data" \
--header 'Content-Type: application/x-www-form-urlencoded' \
--user ${client}:${secret} \
--$verbosity"
response=$(curl $curl_opts "${oaas_uri}/oauth/token")
token=$(parse_json "$response" 'access_token')
if [ $? -eq 0 ]; then
echo $token
else
echo "Failed with response: $response" >&2
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment