Skip to content

Instantly share code, notes, and snippets.

@richeney
Last active March 22, 2021 19:39
Show Gist options
  • Save richeney/1a3ebd4e3e74898abbfea1418baee6b8 to your computer and use it in GitHub Desktop.
Save richeney/1a3ebd4e3e74898abbfea1418baee6b8 to your computer and use it in GitHub Desktop.
Creates and displays a token if a resource is specified. Defaults to https://management.azure.com. Designed for Azure Arc VMs.
#/bin/bash
error()
{
[[ -n "$@" ]] && echo "ERROR: $@" >&2
exit 1
}
urlencode() {
# urlencode <string>
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%s' "$c" | xxd -p -c1 | while read c
do printf '%%%s' "$c"
done ;;
esac
done
}
urldecode() {
# urldecode <string>
local url_encoded="${1//+/ }"
printf '%b' "${url_encoded//%/\\x}"
}
## Main
resource=${1:-management.azure.com}
resource=https://${resource#https://}
resources="https://dev.azuresynapse.net
https://graph.windows.net/
https://management.azure.com/
https://management.core.windows.net/
https://storage.azure.com/
https://vault.azure.net
"
echo "$resources" | grep -q "$resource" || error "Unexpected resource (aud) specified: $resource"
uri="http://127.0.0.1:40342/metadata/identity/oauth2/token?api-version=2019-11-01&resource=$(urlencode $resource)"
challengeTokenPath=$(curl -sD - -H Metadata:true "$uri" | grep Www-Authenticate | cut -d "=" -f 2 | tr -d "[:cntrl:]")
challengeToken=$(sudo cat $challengeTokenPath)
curl -s -H "Metadata:true" -H "Authorization: Basic $challengeToken" "$uri" | jq -r .access_token
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment