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.Core;
using Azure.Identity;
using Microsoft.Identity.Client;
public static 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"))
.WithClientAssertionCallback(async () =>
{
var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(
new TokenRequestContext(new[] { $"https://login.microsoftonline.com/Your-Tenant-Id/.default" })
);
return token.Token;
})
.Build();
var userAssertion = new UserAssertion(userAccessToken);
try
{
var result = await confidentialClientApplication
.AcquireTokenOnBehalfOf(scopes, userAssertion)
.ExecuteAsync();
return result.AccessToken;
}
catch (Exception ex)
{
Console.WriteLine($"Token acquisition failed: {ex.Message}");
return null;
}
}
Replaces .WithCertificate() (which requires an X.509 certificate) with .WithClientAssertionCallback(), which is correct for Managed Identity authentication. Uses DefaultAzureCredential to fetch a token from the Managed Identity. Correctly acquires an On-Behalf-Of (OBO) token.
This should resolve the error.
If the answer is helpful, please click "Accept Answer" and kindly upvote it.