AzureAD/azure-activedirectory-library-for-python

The result token's `resource` doesn't match `resource` sent to `acquire_token_with_device_code`

jiasli opened this issue · 2 comments

https://github.com/Azure/azure-cli/blob/14cc787d0f58bc649d402b486fdecc5625eee9ac/src/azure-cli-core/azure/cli/core/_profile.py#L936-L938

        code = context.acquire_user_code(auth_resource or resource, _CLIENT_ID)
        logger.warning(code['message'])
        token_entry = context.acquire_token_with_device_code(resource, code, _CLIENT_ID)

Azure CLI

  • first sends https://containerregistry.azure.net as resource to acquire_user_code
  • then sends https://management.core.windows.net as resource to acquire_token_with_device_code

In the second step, the date sent to https://login.microsoftonline.com/common/oauth2/token is confirmed to be

grant_type=device_code&client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46&resource=https%3A%2F%2Fmanagement.core.windows.net%2F&code=xxx

But the returned token entry has

"resource": "https://containerregistry.azure.net"

This results in Azure CLI command failure:

> az login --scope https://containerregistry.azure.net/.default --use-device-code

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxx to authenticate.

(InvalidAuthenticationTokenAudience) The access token has been obtained for wrong audience or resource 'https://containerregistry.azure.net'. It should exactly match with one of the allowed audiences 'https://management.core.windows.net/','https://management.core.windows.net','https://management.azure.com/','https://management.azure.com'.

This breaks conditional access MFA scenario.

According to https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code#authenticating-the-user, it looks like scope/resource is not supported by the service API at all. In other words, we cannot alter resource in step 2.

The underlying Device Code Flow specs never defines a scope (or resource, for that matter) in the second leg. The ADAL Python's API surface happened to contain a resource parameter for the second step. That was a design mistake.

MSAL Python avoids this mistake by not accepting a scope parameter in the second step at all.

Thanks for reporting this. The workaround in ADAL Python is "do not use the resource parameter in the second step". And the better solution is to "migrate to MSAL Python", which Azure CLI will do soon. I'll still have to mark this as WontFix here.

Thanks you so much @rayluo. I am only opening this issue for others who bump into it.