简体   繁体   中英

Azure oAuth token retrieval with user managed identity

I am new to Azure. I have an app service and a system managed and an user managed identity. I want to use the rest endpoint to get the access tokens. Based on a config flag, I want to use either

  1. Use the User Managed Identity to get the access tokens. or
  2. Use the system managed identity to get the access tokens.

Since I am new, I am not sure about which endpoint to call. Most importantly, I want to under as to how I can request the AAD to use User Managed Identity over the system managed.

I tried to reproduce the same in my environment and got below results:

I have one App service where I enabled system-assigned managed identity like below:

在此处输入图像描述

Now, Open Kudu by selecting Advanced Tools in your App Service like below:

在此处输入图像描述

In new tab, Kudo will be opened where you need to select PowerShell under Debug console like below:

在此处输入图像描述

Now, run the below PowerShell script to get access token using System-assigned managed identity :

$resourceURI = "https://storage.azure.com"
$tokenAuthURI = $env:IDENTITY_ENDPOINT + "?resource=$resourceURI&api-version=2019-08-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"X-IDENTITY-HEADER"="$env:IDENTITY_HEADER"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

Response:

在此处输入图像描述

You can run $accessToken to print the token like below:

在此处输入图像描述

I added one user managed identity to the App Service like below:

在此处输入图像描述

To get access token using User assigned Managed Identity , you need to include one of the optional parameters like client_id or principal_id in the script.

You can find values of these parameters from your managed identity:

在此处输入图像描述

In my case, I included client_id in PowerShell script to get token using User assigned managed identity like below:

$resourceURI = "https://storage.azure.com"
$client_id = "b7f92ffb-2a35-402f-adc8-xxxxxxxxxxx"
$tokenAuthURI = $env:IDENTITY_ENDPOINT + "?resource=$resourceURI&api-version=2019-08-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"X-IDENTITY-HEADER"="$env:IDENTITY_HEADER"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

Response:

在此处输入图像描述

You can run $accessToken to print the token like below:

在此处输入图像描述

Based on your requirement, you can change the value of $resourceURI parameter to https://graph.microsoft.com , https://vault.azure.net or https://management.azure.com etc...

Including one of the optional parameters like client_id or principal_id in the script is enough to get access token from User Managed Identity over the system managed.

Reference: Managed identities - Azure App Service | Microsoft

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