Grayson
Grayson

Reputation: 73

Generate auth token for accessing CR in Java

I'm authenticating against Azure using a service principal, and I'd like to convert a shell script to Java. My shell script code essentially does this:

export AAD_ACCESS_TOKEN=$(az account get-access-token --query accessToken -o tsv)

export ACR_REFRESH_TOKEN=$(curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=access_token&service=$REGISTRY&access_token=$AAD_ACCESS_TOKEN" \
    https://$REGISTRY/oauth2/exchange \
    | jq '.refresh_token' \
    | sed -e 's/^"//' -e 's/"$//')
echo "ACR Refresh Token obtained."
# Create the repo level scope
SCOPE="repository:$REPOSITORY:pull"

# to pull multiple repositories passing in multiple scope arguments.
#&scope="repository:repo:pull,push"

export ACR_ACCESS_TOKEN=$(curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=refresh_token&service=$REGISTRY&scope=$SCOPE&refresh_token=$ACR_REFRESH_TOKEN" \
    https://$REGISTRY/oauth2/token \
    | jq '.access_token' \
    | sed -e 's/^"//' -e 's/"$//')
echo "ACR Access Token obtained."

I'm trying to find the Java equivalents for

az account get-access-token --query accessToken -o tsv

and

curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=access_token&service=$REGISTRY&access_token=$AAD_ACCESS_TOKEN" https://$REGISTRY/oauth2/exchange | jq '.refresh_token' | sed -e 's/^"//' -e 's/"$//'

and

curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=refresh_token&service=$REGISTRY&scope=$SCOPE&refresh_token=$ACR_REFRESH_TOKEN" https://$REGISTRY/oauth2/token | jq '.access_token' | sed -e 's/^"//' -e 's/"$//'

but haven't really found any documentation on how to do this using Java. I found this: https://github.com/AzureAD/azure-activedirectory-library-for-java/wiki/Acquire-tokens for acquiring AAD tokens but nothing on that page tells me how to do so using a service principal.

Upvotes: 0

Views: 243

Answers (1)

anquegi
anquegi

Reputation: 11542

You need to implement this curls in java, you can use a restclient like https://github.com/square/okhttp/blob/master/README.md

Upvotes: 0

Related Questions