azure-active-directoryazure-cliaz

az account get-access-token - fails to fetch token in user's context


I have a user managed identity, for which I want to generate a token

I tried in user's context

az login
az account get-access-token --resource "<client-id of user managed identity>"

I get the error

Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' named 'Microsoft Azure CLI'. Send an interactive authorization request for this user and resource.

Regarding the above error, I have come across threads which suggest to add Azure CLI as preAuthorizedApplication. However I did not find this managed identity in App RegistrationsI did find an entry in `Enterprise Applications, but did not find how to pre-authorize Azure CLI here.

I tried to achieve the same in a non-user context

az login --service-principal -u <capp-id>  -p <client-secret> --tenant <tenant-id>
az account get-access-token --resource "<client-id of user managed identity>"

This works.

Why does the command fail in user context? How can I make it work?


Solution

  • Managed Identities do not have app registrations, only a service principal (aka enterprise app).

    The way you are trying to use them is not the way they are meant to be used in my opinion.

    The second one working is actually just the feature of Azure AD that allows an application using the client credentials flow (client id + secret) to acquire a token for any app in the tenant. The token won't have any permissions though, so it wouldn't be valid if you are doing authorization correctly.

    You usually don't want to use the managed identities as token targets, only for acquiring tokens. So if you need to protect an API, you'd need an app registration, where you can then allow Az CLI to call it. You can also define application permissions and allow applications using client credentials flow to access the API with proper authorization.