Hi @Ketan Joshi ,
welcome to the Microsoft Q&A Platform!
Yes, you can indeed use a managed identity in an Azure App Service to obtain an "on-behalf-of" (OBO) token without a client secret.
Enable Managed Identity for your App Service if it isn't already enabled. You can enable either a system-assigned or user-assigned managed identity.
Set Up API Permissions: Ensure that the API you're requesting the token for has appropriate API permissions assigned to the managed identity. This means granting the managed identity permission to access the target API (often through a role or specific permissions in Azure AD).
Use Managed Identity to Obtain the Access Token for the API
- First, acquire an access token for your backend API by using the managed identity with Azure's REST endpoint.
Then, pass this token to the backend API, which will then validate it and issue an on-behalf-of token if necessary.
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.Identity.Client;
public async Task<string> AcquireOnBehalfOfToken(string userAccessToken, string[] scopes)
{
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create("Your-Client-Id")
.WithAuthority(new Uri("https://login.microsoftonline.com/Your-Tenant-Id"))
.WithAzureRegion() // Set your Azure region for optimized token acquisition
.WithCertificate(new DefaultAzureCredential()) // Using managed identity
.Build();
// Creating the User Assertion from the user's token
var userAssertion = new UserAssertion(userAccessToken);
try
{
// Acquiring the token on behalf of the user
var result = await confidentialClientApplication
.AcquireTokenOnBehalfOf(scopes, userAssertion)
.ExecuteAsync();
return result.AccessToken;
}
catch (Exception ex)
{
Console.WriteLine($"Token acquisition failed: {ex.Message}");
return null;
}
}
-
DefaultAzureCredential
automatically picks up the managed identity credentials when run in an Azure environment (such as App Service). -
AcquireTokenOnBehalfOf
is used with the user’s token, andscopes
should contain the resource’s scopes you want access to.
If the answer is helpful, please click "Accept Answer" and kindly upvote it.