简体   繁体   中英

How to Fetch Token to access APIM from Function App with Managed identity

I am trying to access APIM from Azure Function and want APIM to authenticate through Managed Identity Token. I have assigned system assigned identity to the function app.I am following this (sample)[https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#asal] to generate token. In the below line if I give "https://vault.azure.net" to GetAccessTokenAsync method I am getting the token. but I want the audience to be APIM so I provided https://azure-api.net like mentioned in the last line. but I am getting exception. how can I provide the APIM Url to fetch the access token?

using Microsoft.Azure.Services.AppAuthentication;
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");

string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://azure-api.net");

An Update. I think something wrong with listing the resources. because when I give the proper resource name it says resource doesnt exist in the tenant though I can see the subscription is under the same tenant when I run through az cli.

As I mentioned in the comment, you need to Register an application in Azure AD to represent the API , then you can get the token for it(ie with the Application ID URI in the previous link).

string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("<Application ID URI>");

Something you need to know:

You can use azureServiceTokenProvider to get the token for https://vault.azure.net , https://managment.azure.com , because they are all the APIs exposed by Microsoft, ie azure keyvault rest api and azure management rest api , essentially they are all AD App registered by Microsoft, so if you want to get the token for your own API, you need to register the AD App first to represent the API first.

Also, when you use managed identity to get the token, essentially it uses the client credential flow to get the token, actually the managed identity is a service principal(ie enterprise application) managed by azure. Remember to leverage the app role if you need to validate the roles claim when you get the access token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM