Skip to content

This sample describes how Azure API Management (APIM) can centralized authentication and authorizaton of APIs using Entra ID using APIM Policy (validate-jwt) and App Roles of Entra ID.

License

Notifications You must be signed in to change notification settings

microsoft/apim-auth-entraid-with-approles

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ArtifactType Language Description Tags
sample
CLi
This sample describes how Azure API Management (APIM) can centralized authentication and authorizaton of APIs using Entra ID using APIM Policy (validate-jwt) and App Roles of Entra ID.
Azure, EntraID, API Management

API Authentication with API Management (APIM) and Entra ID using APIM Policies

GitHub GitHub repo size Azure

GitHub last commit

Scenario

The main objective of this LAB is to demonstrate how Azure API Management (APIM) can centralized authentication and authorizaton of APIs using Entra ID using APIM Policy (validate-jwt) and App Roles of Entra ID. This is very usefull when you have legacy APIs, APIs with no OAuth 2.0 / OIDC or even if you need to centralized management of authentication and authentication in one single pane of glass Topology

Prerequisites

Create APIM Environment

Open Azure Portal and click on Cloud Shell to run this scripts to Create API Management

Variable block

resourceGroup="apim-auth"
ident=$(az account show --query id --output tsv)
ident+=$(echo $resourceGroup)
randomIdentifier=$(echo $ident | md5sum | cut -c 1-7)
apim="$resourceGroup-$randomIdentifier"

Create Resource Group

az group create \
    --name $resourceGroup \
    --location brazilsouth

Ceate an API Management

az apim create --name $apim --resource-group $resourceGroup \
  --publisher-name Contoso --sku-name Developer --publisher-email admin@contoso.com \
  --no-wait

Import an API in APIM

For this demo, we will use Confere API (https://conferenceapi.azurewebsites.net), a backend API for demos proposed, provided by Microsoft. Use this guide Tutorial: Import and publish your first API for more details if need to import API to your API Management.

  1. In the Azure portal, search for and select API Management services.
  2. On the API Management services page, select your API Management instance.
  3. In the left navigation of your API Management instance, select APIs.
  4. Select the OpenAPI tile.
  5. In the Create from OpenAPI specification window, select Full.
  6. Enter the values from the following table.
  7. Click Save

Topology

Setting Value
OpenAPI specification https://conferenceapi.azurewebsites.net?format=json
Display name After you enter the OpenAPI specification URL, API Management fills out this field based on the JSON.
Name After you enter the OpenAPI specification URL, API Management fills out this field based on the JSON.
Products Unlimited
Gateways Managed
Subscription required Unchecked

After you import, lets uncheck the option of subscription required.

In this case, for simplicity of demonstration, we will not use Subscrition feature of APIM, but you can use, on top of Entra ID Authentication and Authorization.

  1. Go to the API imported / All Operations / Settings tab.
  2. Uncheck "Subscription required"

Topology

Register the API App

Create the API entity on Microsoft Entra ID

  1. Navigate to the Azure portal and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. In the Register an application page that appears, enter your application's registration information:
Setting Value
Name apim-auth-api
Supported account types Accounts in this organizational directory only

Select Register to create the application.

In the Overview blade, find and note the Application (client) ID and Directory (tenant) ID. Keep these values for future use.

Expose the API and Publish Delegated Permissions

In the left menu, in Manage section, select the Expose an API blade

This the page where you can publish the permission as an API for which client applications can obtain access tokens for. The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API.

Declare an resource URI(Application ID URI), follow the following steps:

  1. Select Add next to the Application ID URI to generate a URI that is unique for this app.
  2. For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting Save. Read more about Application ID URI at Validation differences by supported account types (signInAudience).

Publish Delegated Permissions

In the same page, add a scope to you App Registration.

All APIs must publish a minimum of one scope, also called Delegated Permission, for the client's to obtain an access token for a user successfully.

To publish a scope, follow these steps:

  1. Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
Setting Value Comment
Scope name APIMAuth.Read (case-sensitive)
Who can consent? Admins and users
Admin consent display name Allow the admins of the app apim-auth to read data
Admin consent description Allows the admins to read the signed-in users data
User consent display name Allow Users to read data items as yourself
User consent description Allow the users to read data on your behalf
State Enabled

Create App Roles

App Roles is the core of RBAC for APIs. We will create two App Roles, one representing "Member Access", and other one representing "Admin" access.

Create the App Role: APIMAuth.Members

  1. Still on the same app registration, select the App Roles blade to the left.
  2. Select Create app role. Create a App Role with the folowing values:
Setting Value
Display name APIMAuth.Members
Allowed member types Both (Users/Groups + Applications)
Value APIMAuth.Members
Description Allow users to access members permissions of API, whitch is: Can list only sessions
Do you want to enable this app role? checked
  1. Select Apply to save your changes.

Create the App Role: APIMAuth.Admins

Repeat the steps above for another app permission named APIMAuth.Admins

Setting Value
Display name APIMAuth.Admins
Allowed member types Both (Users/Groups + Applications)
Value APIMAuth.Admins
Description Allow users to access admin permissions of API, whicth is can list all sessions and speakers
Do you want to enable this app role? checked

Giving users permissions

Next, we will assign users to preview created App Roles. You must have at least two users in your Microsoft Entra ID Tenant, to give one the access of Member, and other the access of Admin.

  1. Still on App Registration pane, on Overview, click on "Managed application in local directory", to go to the Enterprise Application pane. Enterprise Pane
  2. In the Enterprise Application Pane, in Manage section, go to Users and groups, + Add user/group, select a user and select just APIM.Members App Role. Click on Select, and then Assign.
  3. Do the seme for another user, including this time, the APIM.Admins and APIM.Members App Role. The configuration will be something similar to this: Enterprise Pane In this example, Marcos will have the "Admin" role, and Gabriel will have "Member" role.

Configure APIM According App Roles

In this sample, we will consider that Members can list the sessions, but not list the Speakers. To do so, we will configure 2 operations policies, one for GetSessions operation, and another one for GetSpeakers operation.

GetSessions Operation Policy: Validade JWT

  1. In Azure Portal, go to API Management, click on instance created.
  2. In the left panel, go to API, click on API just imported, GetSessions operation. In Inbound policy, click on + Add policy. Enterprise Pane
  3. Select "Validade JWT" Policy.

Enterprise Pane

  1. Fill the values with values of application, described in the table.

Note that you will need the values kept in Microsoft Entra ID / App Registration: Application (client) ID, and Directory (tenant) ID values.

Setting Value
Header name Authorization
Failed validation HTTP code Leave with 401 - Unauthorized
Failed validation error message Unauthorized due APIM Policy
Audiences api://[your-app-id]
[your-app-id]
Required claims - Name roles
Required claims - Match Any claim
Required claims - Value APIMAuth.Members
Open ID URLs https://login.microsoftonline.com/[*your-tenant-id*]/v2.0/.well-known/openid-configuration
  1. Click Save.

  2. Open the policy and add the issuer xml section, below to audiences section

    <issuers>
        <issuer>https://sts.windows.net/[your-tenant-id]/</issuer>
    </issuers>

Final result will be something smimilar to this: Enterprise Pane

GetSpeakers Operation Policy: Validade JWT

Repeat the process with GetSpeakers, using APIMAuth.Admins Role.

Run and Test

At this point you have all setup with your API to be consumed via Entra ID Authentication and Authorization. You can now call the API with a apropriate Barear token aquired against Microsoft Entra ID, with the users you defined at App Roles.

For demonstration proposes in this case, we will aquire a Bearer token via CLi and will use this token to call the APIs. Acording to users we defined in Users / App Roles, users will have access to APIs or not.

Set up Azure CLI

Have Azure CLI installed on your machine. Your can setup folowing this guide: How to install the Azure CLI.

Execute on cli:

az login --use-device-code

Follow the instructions to login with device code with the first user you define in the Microsoft Entra ID / App Roles, with APIMAuth.Members

Enterprise Pane

Next, execute this command:

az account get-access-token --resource api://*your-app-id*

You should see a message like this, saying that the CLi console do not have a consent of admin to ask a token. The Message also give you the CLi ID.

Enterprise Pane

To to this consent, go to Microsoft Entra ID / App Registrations / All application tab / apim-auth-api App. Go to Expose API (same pane of before section), in Authorized client applicaitons, click on +Add a client application and add the CLi ID captured on error message before, selecting the scope previously created

Enterprise Pane

Now, execute again the commands:

az logout
az login --use-device-code

And try to get again the token:

az account get-access-token --resource api://*your-app-id*

You now should get the access token:

Enterprise Pane

If you open https://jwt.ms/ and put the token you will see the claims that Entra ID returned to application, and also will see the Roles that this user was assinged. In my case, the user semedo@oikawa.dev.br was assigned just with APIMAuth.Members role.

Enterprise Pane

Calling Sesions Endpoint

Now you can call the API using this Barear token. You can see the base endpoint your API in API Management / API / Conference API / Settings / Base URL Get the base URL and add the /sessions and /speakers

It will be something like:

https://apim-auth-[yourRandom].azure-api.net/sessions

To call an API with a Barear token, just add a header Authorization with the value "Barear [your token]"

Enterprise Pane

You shoud get and 200 with all sessions of the API.

Calling Skeakers Endpoint

Now let's try to call the speakers endpoint:

https://apim-auth-[yourRandom].azure-api.net/speakers

Enterprise Pane

You shoud get a 401 Unauthorized, with the message previously configured "Unauthorized due APIM Policy"

Calling Skeakers Endpoint with APIMAuth.Admins Role

Now Follow this steps of the section, using now the user you provide with APIMAuth.Admins role. Get the token with the user and call the /speakers endpoint. You shoud see a token with roles in the https://jwt.ms/:

Enterprise Pane

And if you call now the /speakers endpoint with this Barear token, you should see a 200 result.

Enterprise Pane

Learn more

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

About

This sample describes how Azure API Management (APIM) can centralized authentication and authorizaton of APIs using Entra ID using APIM Policy (validate-jwt) and App Roles of Entra ID.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published