Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chgeuer/1dcc185ca53b36d1f365638365be9a95 to your computer and use it in GitHub Desktop.
Save chgeuer/1dcc185ca53b36d1f365638365be9a95 to your computer and use it in GitHub Desktop.

Access KeyVault on customer side with a service principal

#!/bin/bash

# ISV side
app_id_in_isv_tenant="9eb849dd-f1fd-47fc-a3b0-de6a11148049"
client_secret="..."

# customer side
aadTenantCustomer="chgeuerfte.onmicrosoft.com"
cmd.exe /C "start $( echo "https://login.microsoftonline.com/${aadTenantCustomer}/adminconsent?client_id=${app_id_in_isv_tenant}" )"
app_id_in_customer_tenant="9eb849dd-f1fd-47fc-a3b0-de6a11148049"

# OAuth v2.0 token endpoint

access_token="$(curl \
  --silent \
  --request POST \
  --url "https://login.microsoftonline.com/${aadTenantCustomer}/oauth2/v2.0/token" \
  --data-urlencode "response_type=token" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "client_id=${app_id_in_customer_tenant}" \
  --data-urlencode "client_secret=${client_secret}" \
  --data-urlencode "scope=https://vault.azure.net/.default" \
  | jq -r ".access_token" )"

jq -R 'split(".") | .[1] | @base64d | fromjson' <<< "${access_token}"

access_token="$( curl \
  --silent \
  --request POST \
  --url "https://login.microsoftonline.com/${aadTenantCustomer}/oauth2/token" \
  --data-urlencode "response_type=token" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "client_id=${app_id_in_customer_tenant}" \
  --data-urlencode "client_secret=${client_secret}" \
  --data-urlencode "resource=https://vault.azure.net" \
  | jq -r ".access_token" )"

jq -R 'split(".") | .[1] | @base64d | fromjson' <<< "${access_token}"

apiVersion="7.0"
key_vault_name="chgeuergithub2"
secret_name="demosecret"

secretVersion="$( curl --silent --get \
  --url "https://${key_vault_name}.vault.azure.net/secrets/${secret_name}/versions" \
  --data-urlencode "api-version=${apiVersion}" \
  --header "Authorization: Bearer ${access_token}" \
  | jq -r '.value | sort_by(.attributes.created) | .[-1].id' )"

secret="$( curl --silent \
  --url "${secretVersion}?api-version=${apiVersion}" \
  --header "Authorization: Bearer ${access_token}" \
  | jq -r '.value' )"

echo "${secret}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment