How to implement with oidc in entra a on behalf of scenario ?
Private research annotation
Sign in to add a private research label or note.
- User
How to implement with oidc in entra a on behalf of scenario ?
Assistant
Sign in to add a private research label or note.
How to implement with oidc in entra a on behalf of scenario ?
Implementing the OAuth 2.0 On-Behalf-Of (OBO) flow with OpenID Connect (OIDC) in Microsoft Entra ID (formerly Azure AD) involves a few key steps. Here's a breakdown of the implementation process, considerations, and code snippets to guide you:
Understanding the On-Behalf-Of (OBO) Flow
The OBO flow enables a service (the middle-tier or calling service) to act on behalf of a user and access a downstream API. Here's a simplified flow:
Steps for Implementation
Register Applications in Entra ID (Azure AD):
Client Application (Web App or Native App):
user_impersonation or similar). Make sure the user has consented to these permissions.Middle-Tier Service (API):
acceptedAccessTokenVersion in the application manifest. It should be set to 2 for the recommended v2.0 endpoint support. This helps with token validation.Downstream API (Resource API):
ReadData, WriteData). These are application permissions that the middle-tier service will request on behalf of the user.Configure API Permissions:
Code Implementation (Middle-Tier Service):
Authentication: Your middle-tier service needs to authenticate requests from the client application. Verify the access token sent by the client is valid (issued by Entra ID, not expired, correct audience). Libraries like Microsoft.Identity.Web in .NET or equivalent libraries in other languages will handle token validation.
OBO Exchange: Use the Microsoft Authentication Library (MSAL) to perform the OBO exchange. This is the crucial step.
// .NET Example using Microsoft.Identity.Web (Minimal API)
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
// Add authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
// Add MSAL.NET for OBO flow
builder.Services.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi:GraphApi")); // Example for Microsoft Graph
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/obo", async (HttpContext context, ITokenAcquisition tokenAcquisition) =>
{
try
{
string[] scopes = new string[] { "DownstreamApi.Read" }; // Replace with your actual downstream API scopes
string accessTokenForDownstreamApi = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
// Call the downstream API with the access token
// ... (Make the HTTP request to the downstream API)
// Example using HttpClient:
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessTokenForDownstreamApi);
var response = await httpClient.GetAsync("https://your-downstream-api.example.com/data"); // Replace with the actual URL
var content = await response.Content.ReadAsStringAsync();
return Results.Ok(content);
}
catch (Exception ex)
{
// Handle errors during token acquisition (e.g., consent required)
return Results.Problem($"Error acquiring token: {ex.Message}");
}
})
.RequireAuthorization(); // Protect the endpoint with authorization
app.Run();
Not yet included in a published release.
Explanation of the .NET code:
AddMicrosoftIdentityWebApi: This method, from Microsoft.Identity.Web, configures authentication for your middle-tier API using JWT Bearer authentication and integrates with Azure AD. It relies on the AzureAd section in your appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/", // or "https://login.microsoftonline.us" for US Government
"Domain": "your-tenant.onmicrosoft.com",
"TenantId": "YOUR_TENANT_ID",
"ClientId": "YOUR_MIDDLE_TIER_CLIENT_ID", // Client ID of the middle-tier app registration
"ClientSecret": "YOUR_MIDDLE_TIER_CLIENT_SECRET", // Client secret for the middle-tier app registration - KEEP THIS SECRET! Use Key Vault!
"Audience": "api://YOUR_MIDDLE_TIER_CLIENT_ID" // API URL for the service (same as Client ID)
},
"DownstreamApi": {
"Scopes": "DownstreamApi.Read" // Scopes to request for the downstream API
}
}
ITokenAcquisition.GetAccessTokenForUserAsync: This is the core of the OBO flow. It uses the validated access token from the incoming request (handled by the authentication middleware) to request a new access token for the downstream API. It automatically handles the token cache and refreshing tokens when necessary.
Scopes: The scopes parameter is an array of strings representing the scopes (permissions) required from the downstream API. Ensure these match the delegated permissions you configured in the Entra ID app registration. Important: The scopes must be fully qualified with the downstream API's application ID URI (e.g., api://YOUR_DOWNSTREAM_API_CLIENT_ID/DownstreamApi.Read).
Error Handling: The try...catch block is critical. The most common error is that the user has not consented to the required permissions. In a real application, you would handle this gracefully, potentially redirecting the user to a consent page. You can use ex.Message to diagnose the error.
Calling the Downstream API: The code then uses the acquired access token to make an authenticated request to the downstream API.
Other Languages (Node.js, Python, etc.): Use MSAL libraries (e.g., msal-node, `msal-