Skip to content

Commit e92b02e

Browse files
authored
Enable secretless OBO authentication in DAB using Workload Identity Federation (#3880)
## Why make this change? Related to #3641. Existing Azure SQL On-Behalf-Of (OBO) authentication requires an application client secret. This change adds a secretless alternative using managed identity federation, reducing secret-management overhead while preserving the caller's delegated SQL identity and existing client-secret configurations. ## What is this change? - Add `DAB_OBO_MANAGED_IDENTITY_CLIENT_ID` to select a user-assigned managed identity as the OBO application credential. - Introduce `OboCredentialFactory`, which acquires a managed-identity token for `api://AzureADTokenExchange/.default` and supplies it through MSAL's asynchronous client-assertion callback. The caller's access token remains the separate OBO user assertion. - Share credential validation between startup and runtime configuration validation. When OBO is enabled, require the API application/tenant IDs and exactly one credential method: client secret or managed identity federation. - Reuse the credential and confidential client, support fresh assertion acquisition, preserve cancellation, and sanitize managed-identity acquisition errors without credential fallback. - Add credential-factory, configuration and startup tests, together with federation configuration and troubleshooting documentation. The federation option uses a same-tenant user-assigned managed identity on Azure public cloud, with a federated identity credential configured on the API app registration. Existing client-secret deployments remain supported. No new JSON configuration properties or CLI flags are introduced, and the existing SQL permissions/RLS model is unchanged. ## How was this tested? - [x] Integration Tests - [x] Unit Tests **Manual Azure integration validation** - Deployed the feature build to Azure App Service backed by Azure SQL using a Visual Studio subscription, and verified the deployed binaries against the feature build. - Configured and exercised managed-identity federation without an application client secret. - Completed real browser testing with two separate users. Each user could retrieve their own salary data, while SQL RLS prevented access to the other user's data. **Local automated validation** The focused unit/regression suite passed **142 tests**, with **0 failures and 0 skipped tests**. Coverage includes credential selection, missing/conflicting configuration, separate application and user assertions, assertion reacquisition, cancellation, sanitized failures, startup registration and existing OBO regressions. The full solution build passed with **0 warnings and 0 errors**. Commands executed from the repository root: ```powershell # PASSED: 0 warnings, 0 errors. dotnet build .\src\Azure.DataApiBuilder.sln --no-restore --verbosity minimal # PASSED: 142 tests; 0 failed; 0 skipped. dotnet test .\src\Service.Tests\Azure.DataApiBuilder.Service.Tests.csproj --no-restore --filter "FullyQualifiedName~OboCredentialFactoryTests|FullyQualifiedName~OboSqlTokenProviderUnitTests|(FullyQualifiedName~ConfigValidationUnitTests&FullyQualifiedName~UserDelegatedAuth)|FullyQualifiedName~StartupTests.RegisterOboServices|FullyQualifiedName~SqlQueryExecutorUnitTests.SetManagedIdentityAccessToken_Obo" --logger "console;verbosity=minimal" ``` ## Sample Request(s) On an Azure host with the user-assigned managed identity attached, federated trust configured, and the existing OBO configuration and SQL permissions in place: ```powershell $env:DAB_OBO_CLIENT_ID = "<api-app-client-id>" $env:DAB_OBO_TENANT_ID = "<tenant-id>" $env:DAB_OBO_MANAGED_IDENTITY_CLIENT_ID = "<user-assigned-managed-identity-client-id>" Remove-Item Env:\DAB_OBO_CLIENT_SECRET -ErrorAction SilentlyContinue dab start ``` The API request contract is unchanged. For an existing configured `Salary` entity: ```http GET /api/Salary ``` Authenticate the request using the caller's DAB-audience access token with bearer authentication. Federation changes how DAB authenticates its application identity during the OBO exchange; SQL access continues to use the delegated user's identity and permissions.
1 parent 415b56a commit e92b02e

7 files changed

Lines changed: 1402 additions & 163 deletions

File tree

‎src/Config/ObjectModel/DataSource.cs‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -137,19 +137,24 @@ public record MsSqlOptions(bool SetSessionContext = true) : IDataSourceOptions;
137137
/// On-Behalf-Of flow. This allows DAB to connect to the database as the actual user, enabling
138138
/// Row-Level Security (RLS) filtering based on user identity.
139139
///
140-
/// OBO requires an Azure AD App Registration (separate from the DAB service's Managed Identity).
141-
/// The operator deploying DAB must set the following environment variables for the OBO App Registration,
142-
/// which DAB reads at startup via Environment.GetEnvironmentVariable():
143-
/// - DAB_OBO_CLIENT_ID: The Application (client) ID of the OBO App Registration
144-
/// - DAB_OBO_TENANT_ID: The Directory (tenant) ID where the OBO App Registration is registered
145-
/// - DAB_OBO_CLIENT_SECRET: The client secret of the OBO App Registration (not a user secret)
140+
/// OBO requires a Microsoft Entra API App Registration, separate from any Managed Identity used by DAB.
141+
/// The operator deploying DAB must set the following common environment variables, which DAB reads at startup:
142+
/// - DAB_OBO_CLIENT_ID: The Application (client) ID of the API App Registration, not a Managed Identity client ID
143+
/// - DAB_OBO_TENANT_ID: The Directory (tenant) ID where the API App Registration is registered
146144
///
147-
/// These credentials belong to the OBO App Registration, which acts as a confidential client to exchange
148-
/// the incoming user JWT for a database access token. The user provides only their JWT; DAB uses the
149-
/// App Registration credentials to perform the OBO token exchange on their behalf.
145+
/// The credential method is process-wide and applies to all data sources with OBO enabled:
146+
/// - Client secret: Set only DAB_OBO_CLIENT_SECRET to the API App Registration's client secret.
147+
/// Existing deployments need no changes.
148+
/// - Managed identity federation: Set only DAB_OBO_MANAGED_IDENTITY_CLIENT_ID to the client ID of a
149+
/// same-tenant User-Assigned Managed Identity configured as a federated identity credential on the API App Registration.
150+
/// The Managed Identity client ID is distinct from the API App Registration ID in DAB_OBO_CLIENT_ID.
151+
/// DAB selects the method from the credential that is set. When OBO is enabled, configuring both or neither
152+
/// credential is an error. Blank values count as unset. Leave the other method's credential variable unset.
150153
///
151-
/// These can be set in the hosting environment (e.g., Azure Container Apps secrets, Kubernetes secrets,
152-
/// Docker environment variables, or local shell environment).
154+
/// The API App Registration acts as a confidential client to exchange the incoming user JWT for a database
155+
/// access token. The user provides only their JWT; DAB uses the configured credential for the OBO exchange.
156+
/// Environment variables can be set in the hosting environment (e.g., Azure Container Apps secrets,
157+
/// Kubernetes secrets, Docker environment variables, or the local shell).
153158
///
154159
/// Note: DAB-specific prefixes (DAB_OBO_*) are used instead of AZURE_* to avoid conflict with
155160
/// DefaultAzureCredential, which interprets AZURE_CLIENT_ID as a User-Assigned Managed Identity ID.
@@ -170,22 +175,31 @@ public record UserDelegatedAuthOptions(
170175
public const int DEFAULT_TOKEN_CACHE_DURATION_MINUTES = 45;
171176

172177
/// <summary>
173-
/// Environment variable name for OBO App Registration client ID.
178+
/// Environment variable name for the API App Registration client ID, required for either OBO credential method.
179+
/// This is not the client ID of the Managed Identity used for federation.
174180
/// Uses DAB-specific prefix to avoid conflict with AZURE_CLIENT_ID which is
175181
/// interpreted by DefaultAzureCredential/ManagedIdentityCredential as a
176182
/// User-Assigned Managed Identity ID.
177183
/// </summary>
178184
public const string DAB_OBO_CLIENT_ID_ENV_VAR = "DAB_OBO_CLIENT_ID";
179185

180186
/// <summary>
181-
/// Environment variable name for OBO App Registration client secret.
182-
/// Used for On-Behalf-Of token exchange.
187+
/// Environment variable name for the API App Registration client secret.
188+
/// Selects the client-secret OBO method when set; leave unset for managed identity federation.
183189
/// </summary>
184190
public const string DAB_OBO_CLIENT_SECRET_ENV_VAR = "DAB_OBO_CLIENT_SECRET";
185191

186192
/// <summary>
187-
/// Environment variable name for OBO tenant ID.
193+
/// Environment variable name for OBO tenant ID, required for either credential method.
188194
/// Uses DAB-specific prefix for consistency with OBO client ID.
189195
/// </summary>
190196
public const string DAB_OBO_TENANT_ID_ENV_VAR = "DAB_OBO_TENANT_ID";
197+
198+
/// <summary>
199+
/// Environment variable name for the User-Assigned Managed Identity client ID; selects federation when set.
200+
/// The identity must be in the API App Registration's tenant and configured as its federated identity credential.
201+
/// This is distinct from DAB_OBO_CLIENT_ID; its selection is independent of AZURE_CLIENT_ID and startup metadata access.
202+
/// Leave unset for client-secret authentication.
203+
/// </summary>
204+
public const string DAB_OBO_MANAGED_IDENTITY_CLIENT_ID_ENV_VAR = "DAB_OBO_MANAGED_IDENTITY_CLIENT_ID";
191205
}
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System.Net;
5+
using Azure.Core;
6+
using Azure.DataApiBuilder.Config.ObjectModel;
7+
using Azure.DataApiBuilder.Service.Exceptions;
8+
using Azure.Identity;
9+
using Microsoft.Extensions.Logging;
10+
using Microsoft.Identity.Client;
11+
12+
namespace Azure.DataApiBuilder.Core.AuthenticationHelpers
13+
{
14+
/// <summary>
15+
/// Validates and creates the application credential used for user-delegated authentication.
16+
/// </summary>
17+
public static class OboCredentialFactory
18+
{
19+
public const string MISSING_CREDENTIALS_ERROR_MESSAGE =
20+
"User-delegated authentication requires DAB_OBO_CLIENT_ID, DAB_OBO_TENANT_ID, and exactly one of DAB_OBO_CLIENT_SECRET or DAB_OBO_MANAGED_IDENTITY_CLIENT_ID.";
21+
22+
private const string CONFLICTING_CREDENTIALS_ERROR_MESSAGE =
23+
"Configure exactly one OBO credential method. DAB_OBO_CLIENT_SECRET and DAB_OBO_MANAGED_IDENTITY_CLIENT_ID cannot both be set.";
24+
25+
private const string TOKEN_EXCHANGE_SCOPE = "api://AzureADTokenExchange/.default";
26+
27+
/// <summary>
28+
/// Validates the environment variables for the selected OBO application credential.
29+
/// Callers are responsible for checking whether user-delegated authentication is enabled.
30+
/// </summary>
31+
public static void ValidateEnvironmentVariables()
32+
{
33+
ValidateEnvironmentVariables(Environment.GetEnvironmentVariable);
34+
}
35+
36+
/// <summary>
37+
/// Creates a confidential client whose credential is independent of the incoming user assertion.
38+
/// The returned client should be reused for subsequent OBO requests.
39+
/// </summary>
40+
public static IConfidentialClientApplication CreateClient(ILogger logger)
41+
{
42+
return CreateClient(logger, Environment.GetEnvironmentVariable);
43+
}
44+
45+
internal static void ValidateEnvironmentVariables(Func<string, string?> environmentVariableReader)
46+
{
47+
_ = ReadOptions(environmentVariableReader);
48+
}
49+
50+
internal static IConfidentialClientApplication CreateClient(
51+
ILogger logger,
52+
Func<string, string?> environmentVariableReader,
53+
Func<string, TokenCredential>? managedIdentityCredentialFactory = null,
54+
IMsalHttpClientFactory? httpClientFactory = null)
55+
{
56+
ArgumentNullException.ThrowIfNull(logger);
57+
OboCredentialOptions options = ReadOptions(environmentVariableReader);
58+
59+
ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder
60+
.Create(options.ClientId)
61+
.WithAuthority(AzureCloudInstance.AzurePublic, options.TenantId);
62+
63+
if (options.ClientSecret is not null)
64+
{
65+
builder.WithClientSecret(options.ClientSecret);
66+
}
67+
else
68+
{
69+
TokenCredential credential = managedIdentityCredentialFactory is null
70+
? new ManagedIdentityCredential(ManagedIdentityId.FromUserAssignedClientId(options.ManagedIdentityClientId!))
71+
: managedIdentityCredentialFactory(options.ManagedIdentityClientId!);
72+
73+
// Reuse the credential, not a token snapshot: Azure Identity handles assertion refresh.
74+
builder.WithClientAssertion((AssertionRequestOptions requestOptions) =>
75+
GetManagedIdentityAssertionAsync(credential, logger, requestOptions.CancellationToken));
76+
}
77+
78+
if (httpClientFactory is not null)
79+
{
80+
builder.WithHttpClientFactory(httpClientFactory);
81+
}
82+
83+
return builder.Build();
84+
}
85+
86+
private static async Task<string> GetManagedIdentityAssertionAsync(
87+
TokenCredential credential,
88+
ILogger logger,
89+
CancellationToken cancellationToken)
90+
{
91+
try
92+
{
93+
cancellationToken.ThrowIfCancellationRequested();
94+
AccessToken assertion = await credential.GetTokenAsync(
95+
new TokenRequestContext([TOKEN_EXCHANGE_SCOPE]),
96+
cancellationToken).ConfigureAwait(false);
97+
cancellationToken.ThrowIfCancellationRequested();
98+
99+
if (string.IsNullOrWhiteSpace(assertion.Token) || assertion.ExpiresOn <= DateTimeOffset.UtcNow)
100+
{
101+
throw CreateAuthenticationFailure(logger);
102+
}
103+
104+
return assertion.Token;
105+
}
106+
catch (AuthenticationFailedException)
107+
{
108+
// CredentialUnavailableException derives from AuthenticationFailedException.
109+
cancellationToken.ThrowIfCancellationRequested();
110+
throw CreateAuthenticationFailure(logger);
111+
}
112+
}
113+
114+
private static DataApiBuilderException CreateAuthenticationFailure(ILogger logger)
115+
{
116+
// SDK exceptions can contain credential responses. Do not log or retain their payloads.
117+
logger.LogError(
118+
"{EventType}: Unable to acquire the managed identity client assertion for user-delegated authentication.",
119+
"OboClientAssertionAcquisitionFailed");
120+
121+
return new DataApiBuilderException(
122+
message: DataApiBuilderException.OBO_TOKEN_ACQUISITION_FAILED,
123+
statusCode: HttpStatusCode.Unauthorized,
124+
subStatusCode: DataApiBuilderException.SubStatusCodes.OboAuthenticationFailure);
125+
}
126+
127+
private static OboCredentialOptions ReadOptions(Func<string, string?> environmentVariableReader)
128+
{
129+
ArgumentNullException.ThrowIfNull(environmentVariableReader);
130+
131+
string? clientId = environmentVariableReader(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR);
132+
string? tenantId = environmentVariableReader(UserDelegatedAuthOptions.DAB_OBO_TENANT_ID_ENV_VAR);
133+
string? clientSecret = environmentVariableReader(UserDelegatedAuthOptions.DAB_OBO_CLIENT_SECRET_ENV_VAR);
134+
string? managedIdentityClientId = environmentVariableReader(UserDelegatedAuthOptions.DAB_OBO_MANAGED_IDENTITY_CLIENT_ID_ENV_VAR);
135+
bool hasClientSecret = !string.IsNullOrWhiteSpace(clientSecret);
136+
bool hasManagedIdentity = !string.IsNullOrWhiteSpace(managedIdentityClientId);
137+
138+
if (hasClientSecret && hasManagedIdentity)
139+
{
140+
throw CreateConfigurationFailure(CONFLICTING_CREDENTIALS_ERROR_MESSAGE);
141+
}
142+
143+
if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(tenantId)
144+
|| (!hasClientSecret && !hasManagedIdentity))
145+
{
146+
throw CreateConfigurationFailure(MISSING_CREDENTIALS_ERROR_MESSAGE);
147+
}
148+
149+
return new OboCredentialOptions(
150+
clientId,
151+
tenantId,
152+
hasClientSecret ? clientSecret : null,
153+
hasManagedIdentity ? managedIdentityClientId : null);
154+
}
155+
156+
private static DataApiBuilderException CreateConfigurationFailure(string message)
157+
{
158+
return new DataApiBuilderException(
159+
message: message,
160+
statusCode: HttpStatusCode.ServiceUnavailable,
161+
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError);
162+
}
163+
164+
private sealed class OboCredentialOptions
165+
{
166+
public string ClientId { get; }
167+
public string TenantId { get; }
168+
public string? ClientSecret { get; }
169+
public string? ManagedIdentityClientId { get; }
170+
171+
public OboCredentialOptions(
172+
string clientId,
173+
string tenantId,
174+
string? clientSecret,
175+
string? managedIdentityClientId)
176+
{
177+
ClientId = clientId;
178+
TenantId = tenantId;
179+
ClientSecret = clientSecret;
180+
ManagedIdentityClientId = managedIdentityClientId;
181+
}
182+
}
183+
}
184+
}

‎src/Core/Configurations/RuntimeConfigValidator.cs‎

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public class RuntimeConfigValidator : IConfigValidator
6262
"runtime.cache.enabled must be false when user-delegated-auth is configured.";
6363

6464
public const string USER_DELEGATED_AUTH_MISSING_CREDENTIALS_ERR_MSG =
65-
"User-delegated authentication requires DAB_OBO_CLIENT_ID, DAB_OBO_TENANT_ID, and DAB_OBO_CLIENT_SECRET environment variables.";
65+
OboCredentialFactory.MISSING_CREDENTIALS_ERROR_MESSAGE;
6666

6767
// Error messages.
6868
public const string INVALID_CLAIMS_IN_POLICY_ERR_MSG = "One or more claim types supplied in the database policy are not supported.";
@@ -129,16 +129,18 @@ public void ValidateDataSourceInConfig(
129129

130130
/// <summary>
131131
/// Validates configuration for user-delegated authentication (OBO).
132-
/// When any data source has user-delegated-auth configured, the following
132+
/// When any data source has user-delegated-auth enabled, the following
133133
/// rules are enforced:
134134
/// - data-source.database-type must be "mssql".
135135
/// - data-source.user-delegated-auth.database-audience must be present.
136136
/// - runtime.cache.enabled must be false.
137-
/// - Environment variables DAB_OBO_CLIENT_ID, DAB_OBO_TENANT_ID, and DAB_OBO_CLIENT_SECRET must be set.
137+
/// - Environment variables must supply the API app IDs and exactly one process-wide OBO credential: client secret or managed identity.
138138
/// </summary>
139139
/// <param name="runtimeConfig">Runtime configuration.</param>
140140
private void ValidateUserDelegatedAuthOptions(RuntimeConfig runtimeConfig)
141141
{
142+
bool hasValidatedGlobalOptions = false;
143+
142144
foreach (DataSource dataSource in runtimeConfig.ListAllDataSources())
143145
{
144146
// Skip validation if user-delegated-auth is not configured or not enabled
@@ -163,26 +165,27 @@ private void ValidateUserDelegatedAuthOptions(RuntimeConfig runtimeConfig)
163165
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError));
164166
}
165167

166-
// Validate OBO App Registration credentials are configured via environment variables.
167-
string? clientId = Environment.GetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR);
168-
string? tenantId = Environment.GetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_TENANT_ID_ENV_VAR);
169-
string? clientSecret = Environment.GetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_SECRET_ENV_VAR);
170-
171-
if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(clientSecret))
168+
// Credentials and result caching are process-wide; record their errors only once.
169+
if (!hasValidatedGlobalOptions)
172170
{
173-
HandleOrRecordException(new DataApiBuilderException(
174-
message: USER_DELEGATED_AUTH_MISSING_CREDENTIALS_ERR_MSG,
175-
statusCode: HttpStatusCode.ServiceUnavailable,
176-
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError));
177-
}
171+
try
172+
{
173+
OboCredentialFactory.ValidateEnvironmentVariables();
174+
}
175+
catch (DataApiBuilderException ex) when (ex.SubStatusCode == DataApiBuilderException.SubStatusCodes.ConfigValidationError)
176+
{
177+
HandleOrRecordException(ex);
178+
}
178179

179-
// Validate caching is disabled when user-delegated-auth is enabled
180-
if (runtimeConfig.Runtime?.Cache?.Enabled == true)
181-
{
182-
HandleOrRecordException(new DataApiBuilderException(
183-
message: USER_DELEGATED_AUTH_CACHING_ERR_MSG,
184-
statusCode: HttpStatusCode.ServiceUnavailable,
185-
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError));
180+
if (runtimeConfig.Runtime?.Cache?.Enabled == true)
181+
{
182+
HandleOrRecordException(new DataApiBuilderException(
183+
message: USER_DELEGATED_AUTH_CACHING_ERR_MSG,
184+
statusCode: HttpStatusCode.ServiceUnavailable,
185+
subStatusCode: DataApiBuilderException.SubStatusCodes.ConfigValidationError));
186+
}
187+
188+
hasValidatedGlobalOptions = true;
186189
}
187190
}
188191
}

0 commit comments

Comments
 (0)