Search code examples
microsoft-graph-apiazure-cli

Microsoft Graph API authentication without the CLI


From an environment where the Azure cli is and cannot be installed, how can I get an Auth token from a Service Principal? So I can run queries like:

curl -X -H 'Authorization: Bearer <auth-token>' \
    https://graph.microsoft.com/beta/groups

With the CLI this is fairly simple, I have a tenant_id, an azure_client_id and an azure_client_secret:

az login --service-principal -u <az_client_id> -p <az_client_secret> --tenant <tenant_id>

and then run for example:

az rest --method get --url https://graph.microsoft.com/beta/groups

-- attempt 1

I do get an access token with request:

curl -X GET \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    -d 'grant_type=client_credentials&client_id=<azure-client-id>&resource=2ff814a6-3304-4ab8-85cb-cd0e6f879c1d&client_secret=<azure-client-secret>' \
    https://login.microsoftonline.com/<tenant-id>/oauth2/token

but is is apperantly not valid for the Microsoft graph API.


Solution

  • This work for me from Windows Command Prompt:

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default" https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token
    

    Result:

    {
      "token_type":"Bearer",
      "expires_in":3599,
      "ext_expires_in":3599,
      "access_token":"eyJ0...LUEQ"
    }
    

    You are missing scope=https://graph.microsoft.com/.default, request URL should be https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token and method should be POST.

    I used double quotes instead of single quote for header and body parameters.

    Resources:

    Get access without user