Search code examples
azureopenid-connectazure-managed-identitymicrosoft-identity-platform

Call protected web API from client using Azure user managed identity (AADSTS700222 error)


I am trying to replace the clientid & secret with a user managed identity based on this and this and this example/docs.

I am able to connect to Key Vault (as an example) using

    builder.Configuration.AddAzureKeyVault(
    new Uri($"https://{builder.Configuration["KeyVaultName"]}.vault.azure.net/"),
    new DefaultAzureCredential(new DefaultAzureCredentialOptions
    {
        ManagedIdentityClientId = "68223c16-976d-....24b"
    }
        ),
        new AzureKeyVaultConfigurationOptions()
        {
            ReloadInterval = TimeSpan.FromMinutes(1)
        });

}

When I add any downstream services:

enter image description here

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
                .EnableTokenAcquisitionToCallDownstreamApi() 
        .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
                .AddDownstreamApi("MyDownstreamAPI", builder.Configuration.GetSection("MyDownstreamAPI"))          
                .AddInMemoryTokenCaches();

I get a constant login retry (400 bad request) and

AADSTS700222: AAD-issued tokens may not be used for federated identity flows

:

    2023-06-30 01:39:55.088 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: [MsIdWeb] Using Managed identity for client credentials.
2023-06-30 01:39:55.088 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z] ConfidentialClientApplication 45523402 created
2023-06-30 01:39:55.095 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] MSAL MSAL.NetCore with assembly version '4.54.1.0'. CorrelationId(9c30ff44-bf8f-423d-8151-a5b4f6b049bf)
2023-06-30 01:39:55.096 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf]=== Request Data ===Authority Provided? - TrueScopes -Extra Query Params Keys (space separated) -ApiId - AcquireTokenByAuthorizationCodeIsConfidentialClient - TrueSendX5C - FalseLoginHint ? FalseIsBrokerConfigured - FalseHomeAccountId - FalseCorrelationId - 9c30ff44-bf8f-423d-8151-a5b4f6b049bfUserAssertion set: FalseLongRunningOboCacheKey set: FalseRegion configured:
2023-06-30 01:39:55.096 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] === Token Acquisition (ConfidentialAuthCodeRequest) started:Scopes:Authority Host: login.microsoftonline.com
2023-06-30 01:39:55.151 +00:00 [Warning] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Only in-memory caching is used. The cache is not persisted and will be lost if the machine is restarted. It also does not scale for a web app or web API, where the number of users can grow large. In production, web apps and web APIs should use distributed caching like Redis. See https://aka.ms/msal-net-cca-token-cache-serialization
2023-06-30 01:39:55.151 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Instance Discovery] Instance discovery is enabled and will be performed
2023-06-30 01:39:55.151 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Region discovery] Not using a regional authority.
2023-06-30 01:39:55.151 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Instance Discovery] Tried to use network cache provider for login.microsoftonline.com. Success? True.
2023-06-30 01:39:55.151 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Instance Discovery] The network provider found an entry for login.microsoftonline.com.
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Starting TokenClient:SendTokenRequestAsync
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [TokenClient] Before adding the client assertion / secret
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [TokenClient] After adding the client assertion / secret
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Token Client] Fetching MsalTokenResponse ....
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Starting [Oauth2Client] Sending POST request
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Starting [HttpManager] ExecuteAsync
2023-06-30 01:39:55.152 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [HttpManager] Sending request. Method: POST. Host: https://login.microsoftonline.com.
2023-06-30 01:39:55.153 +00:00 [Information] System.Net.Http.HttpClient.Default.LogicalHandler: Start processing HTTP request POST https://login.microsoftonline.com/tenantREDACTED/oauth2/v2.0/token
2023-06-30 01:39:55.153 +00:00 [Trace] System.Net.Http.HttpClient.Default.LogicalHandler: Request Headers:x-client-SKU: MSAL.NetCorex-client-Ver: 4.54.1.0x-client-CPU: x64x-client-OS: Microsoft Windows 10.0.14393x-client-current-telemetry: 5|1000,0,,,|0,0,1x-client-last-telemetry: 5|0|||x-ms-PKeyAuth: 1.0x-anchormailbox: upn:oid:redacted-ms-lib-capability: retry-after, h429client-request-id: 9c30ff44-bf8f-423d-8151-a5b4f6b049bfreturn-client-request-id: truex-app-name: UnknownClientx-app-ver: 0.0.0.0x-client-brkrver: IDWeb.2.11.1.0Content-Type: application/x-www-form-urlencoded
2023-06-30 01:39:55.153 +00:00 [Information] System.Net.Http.HttpClient.Default.ClientHandler: Sending HTTP request POST https://login.microsoftonline.com/tenantredacted/oauth2/v2.0/token
2023-06-30 01:39:55.153 +00:00 [Trace] System.Net.Http.HttpClient.Default.ClientHandler: Request Headers:x-client-SKU: MSAL.NetCorex-client-Ver: 4.54.1.0x-client-CPU: x64x-client-OS: Microsoft Windows 10.0.14393x-client-current-telemetry: 5|1000,0,,,|0,0,1x-client-last-telemetry: 5|0|||x-ms-PKeyAuth: 1.0x-anchormailbox: upn:oid:redacted-ms-lib-capability: retry-after, h429client-request-id: 9c30ff44-bf8f-423d-8151-a5b4f6b049bfreturn-client-request-id: truex-app-name: UnknownClientx-app-ver: 0.0.0.0x-client-brkrver: IDWeb.2.11.1.0Content-Type: application/x-www-form-urlencoded
2023-06-30 01:39:55.528 +00:00 [Information] System.Net.Http.HttpClient.Default.ClientHandler: Received HTTP response headers after 375.3276ms - 400
2023-06-30 01:39:55.528 +00:00 [Trace] System.Net.Http.HttpClient.Default.ClientHandler: Response Headers:Cache-Control: no-store, no-cachePragma: no-cacheStrict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffP3P: CP="DSP CUR OTPi IND OTRi ONL FIN"client-request-id: 9c30ff44-bf8f-423d-8151-a5b4f6b049bfx-ms-request-id: 06809f60-483b-42f1-b1af-9fa137214500x-ms-ests-server: 2.1.15723.3 - NCUS ProdSlicesx-ms-clitelem: 1,700222,0,,X-XSS-Protection: 0Set-Cookie: fpc=ArxWNjTNAK5NvjxwUi64bTyW2jeqAQAAAGspMNwOAAAA; expires=Sun, 30-Jul-2023 01:39:55 GMT; path=/; secure; HttpOnly; SameSite=None, x-ms-gateway-slice=estsfd; path=/; secure; httponly, stsservicecookie=estsfd; path=/; secure; httponlyDate: Fri, 30 Jun 2023 01:39:54 GMTContent-Type: application/json; charset=utf-8Expires: -1Content-Length: 498
2023-06-30 01:39:55.529 +00:00 [Information] System.Net.Http.HttpClient.Default.LogicalHandler: End processing HTTP request after 376.0046ms - 400
2023-06-30 01:39:55.529 +00:00 [Trace] System.Net.Http.HttpClient.Default.LogicalHandler: Response Headers:Cache-Control: no-store, no-cachePragma: no-cacheStrict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffP3P: CP="DSP CUR OTPi IND OTRi ONL FIN"client-request-id: 9c30ff44-bf8f-423d-8151-a5b4f6b049bfx-ms-request-id: 06809f60-483b-42f1-b1af-9fa137214500x-ms-ests-server: 2.1.15723.3 - NCUS ProdSlicesx-ms-clitelem: 1,700222,0,,X-XSS-Protection: 0Set-Cookie: fpc=ArxWNjTNAK5NvjxwUi64bTyW2jeqAQAAAGspMNwOAAAA; expires=Sun, 30-Jul-2023 01:39:55 GMT; path=/; secure; HttpOnly; SameSite=None, x-ms-gateway-slice=estsfd; path=/; secure; httponly, stsservicecookie=estsfd; path=/; secure; httponlyDate: Fri, 30 Jun 2023 01:39:54 GMTContent-Type: application/json; charset=utf-8Expires: -1Content-Length: 498
2023-06-30 01:39:55.529 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [HttpManager] Received response. Status code: BadRequest.
2023-06-30 01:39:55.529 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Finished [HttpManager] ExecuteAsync in 376 ms
2023-06-30 01:39:55.529 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Response status code does not indicate success: 400 (BadRequest).
2023-06-30 01:39:55.534 +00:00 [Warning] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Request retry failed.
2023-06-30 01:39:55.534 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Finished [Oauth2Client] Sending POST request  in 381 ms
2023-06-30 01:39:55.534 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] [Oauth2Client] Processing error response
2023-06-30 01:39:55.534 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] HttpStatusCode: 400: BadRequest
2023-06-30 01:39:55.542 +00:00 [Error] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] === Token Acquisition (1000) failed.Host: login.microsoftonline.com.
2023-06-30 01:39:55.546 +00:00 [Error] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Exception type: Microsoft.Identity.Client.MsalServiceException, ErrorCode: invalid_requestHTTP StatusCode 400CorrelationId 9c30ff44-bf8f-423d-8151-a5b4f6b049bf
2023-06-30 01:39:55.547 +00:00 [Debug] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Finished TokenClient:SendTokenRequestAsync in 395 ms
2023-06-30 01:39:55.560 +00:00 [Error] Microsoft.Identity.Web.TokenAcquisition: False MSAL 4.54.1.0 MSAL.NetCore .NET 6.0.16 Microsoft Windows 10.0.14393 [2023-06-30 01:39:55Z - 9c30ff44-bf8f-423d-8151-a5b4f6b049bf] Exception type: Microsoft.Identity.Client.MsalServiceException, ErrorCode: invalid_requestHTTP StatusCode 400CorrelationId 9c30ff44-bf8f-423d-8151-a5b4f6b049bf
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext, Boolean addCommonHeaders, Func`2 onBeforePostRequestHandler)at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)at Microsoft.Identity.Client.Internal.Requests.RequestBase.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, CancellationToken cancellationToken)at Microsoft.Identity.Client.Internal.Requests.ConfidentialAuthCodeRequest.ExecuteAsync(CancellationToken cancellationToken)at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
2023-06-30 01:39:55.562 +00:00 [Information] Microsoft.Identity.Web.TokenAcquisition: [MsIdWeb] An error occured during token acquisition: Exception occurred while adding an account to the cache from the auth code.MSAL.NetCore.4.54.1.0.MsalServiceException:ErrorCode: invalid_requestMicrosoft.Identity.Client.MsalServiceException: AADSTS700222: AAD-issued tokens may not be used for federated identity flows.Trace ID: 06809f60-483b-42f1-b1af-9fa137214500Correlation ID: 9c30ff44-bf8f-423d-8151-a5b4f6b049bfTimestamp: 2023-06-30 01:39:55Zat Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)at...

I have added a role definition for the managed identity of the webapp (client & API):

az role assignment create --role $role --assignee-object-id $principalId --assignee-principal-type ServicePrincipal --scope $apiAppId

I also added the managed identity to the webapp and API in the Identity blade for User-managed identities.

Is what I'm trying to do possible or recommended? Azure API Management discusses it (but I'm not currently using it): https://learn.microsoft.com/en-us/azure/api-management/authentication-authorization-overview.


Solution

  • I thought as part of a code flow MI token negotiation would take place prior to attempting a user token, but this is incorrect, as clarified by the product team:

    Managed identity is only usable for daemon scenarios..., that is using the Client credential flow (AcquireTokenForApp).

    Microsoft.Identity.Web provides all the confidential client application flows (Auth code flow and refresh token in web apps, On behalf of user / app in web APIs, and client credentials for daemon scenarios), and it does use managed identity either to fetch certificates from KeyVault, and work using workload identity.