Create on behalf of token using managed identity

Ketan Joshi 20 Reputation points Microsoft Employee
2024-10-30T18:26:52.56+00:00

Hello,

I am trying to create an on behalf of token for one of the applications i am building.

I have been following microsoft doc,

and this is the code I see for creating confidential client applications. However, we do not use client secret for any of our entra apps. I wanted to know is there a work around for app services that use managed identity to create on behalf of tokens.


     _app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
            .Build();
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,931 questions
{count} votes

Accepted answer
  1. Shree Hima Bindu Maganti 4,775 Reputation points Microsoft External Staff Moderator
    2024-11-05T07:11:48.16+00:00

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.