Use a CLI to get an access token for your AAD Protected Web API

You have an application registration in your tenant that represents the Web API to secure.

https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview

During development, you may want to make calls to the api without a fully-developed client application. You can use Postman, configuring it to get an access token. (If you are well-versed in the OAuth 2.0 language. ;) )

During recent development work, I have used the REST Client extension for Visual Studio Code. This is a terrific extension that will execute the request right inside the editor, show the full request/response. But, I need to use an Authorization header that needs a token. Now what?

Using the VS Code terminal, I can run the Azure CLI (or the O365 CLI). Both of these have commands to get an access token. As you expect, however, neither of them have consent to get tokens to a custom API.

The solution is to authorize the CLI applications to the Web API in Azure Active directory. On the "Expose an API" blade is a button to "Add a client application". But, that requires entry of the AppId of the CLI application.

You can try using them and spelunk thru the error messages. But I have looked them up for you. :)

Azure CLI: 04b07795-8ddb-461a-bbee-02f9e1bf7b46

O365 CLI: 31359c7f-bd7e-475c-86db-fdb8c937548e

To get the token, use the appropriate command:

az account get-access-token --resource api://97a1ab8b-9ede-41fc-8370-7199a4c16224

o365 accesstoken get -r api://97a1ab8b-9ede-41fc-8370-7199a4c16224

There, right in the windows is a lovely access token. Copy that into the file associated with REST Client and off you go.

Update: Why this works...

The specificed client application is add to the preAuthorizedApplications collection of the app manifest. In effect, the consent is granted for all users of that application. If you controlled the application (the Azure CLI or the O365 CLI, you could write code to prompt for consent to this custom web API [in OAuth words - this custom resource]. But since you do not control those applications, this preAuthorization helps. And since you are using a developer tenant, you are an tenant administrator and have the permission to pre-consent. ;)