06: Accessing Protected API
To access protected API in our Function App, we need to get an access token from Azure AD App.
This diagram shows a high-level view of the authentication flow:
The E2E oauth2 auth code flow is being described here
Generate Client Id and Secret
- To generate an access token to access our APIs, A User first need to onboard their AD App
(Client AD App)
to our AD App(Server AD App)
. However, for demo purpose, we will directly create a secret id and token in Server Ad App. - In AD App Blade in Azure Portal, Select Ad App
functiondemo-ad-server-app
- In
Certificates & secrets
tab, create a new client secret.
Every individual user can create their own client secret either directly in the above server ad app (given they have permission). In case service owner do not want to give permission to Server Ad App directly as it may have access to all API, we can ask them to create their own Ad App (know as client Ad App) and then we can onboard that to our server AD App with required scope/permission. In this way a team can manage users on their own and all of those user will automatically get same level of access as on client app.
Get Azure AD OAuth2 token
export TENANT_ID="xxxxxxx-353f-xxxxxxx-be76-xxxxxx"
export GRANT_TYPE="client_credentials"
export CLIENT_ID="xxxxx-47cd-xxxxxxx-a16e-xxxxxx"
export SCOPE="api://$CLIENT_ID/.default"
read -p "Enter Client Secret: " CLIENT_SECRET
curl --location --request POST "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "grant_type=$GRANT_TYPE" \
--data-urlencode "client_id=$CLIENT_ID" \
--data-urlencode "client_secret=$CLIENT_SECRET" \
--data-urlencode "scope=$SCOPE" | jq .
Above CURL returns an access token which is valid for 1 hour. We need to use this token and authenticate to our Function API. If access token does not have required JWT claims, our code will reject the access.
curl --location --request GET 'http://localhost:7071/vault?secret=name' \
--header 'Authorization: Bearer REDACTED'
Similarly, we can authenticate to Azure Function deployed in Azure Cloud.
curl --location --request GET 'https://function-demo-demo.azurewebsites.net/vault?secret=name' \
--header 'Authorization: Bearer REDACTED'