title: Azure CLI SP creation w/ API permissions
body: <p>I'm trying to write a simple script to create an SP that is assigned some Microsoft Graph API permissions. I think what I need to do is create an SP with a Contributor role, then assign it the API permissions I need from Microsoft Graph API, and then grant admin consent. It does run to completion, however then when I look in the portal admin consent hasn't been granted, and when I then try to assign manually, I get the following:</p>
  <p><code>Grant consent failed with error: Claim is invalid: 204e0828-b5ca-4ad8-b9f3-f32a958e7cc4 does not exist on resource application 00000003-0000-0000-c000-000000000000. [zPYKlPo0GJHRzGclFADr9k]</code></p>
  <p>Here's the script, any suggestions are welcome:</p>
  <pre class="lang-sh prettyprint-override"><code>#!/bin/bash
  
  ## Usage: ./setup-sp.sh &lt;app-name&gt;
  set -eou pipefail
  
  getPermissionId () {
    # $1 = name of permission, e.g. User.ReadWrite.All
    echo `az ad sp list \
      --query &quot;[?appDisplayName=='Microsoft Graph'].{permissions:oauth2Permissions}[0].permissions[?value=='$1'].id&quot; \
      --all \
      --output tsv`
  }
  
  APP_NAME=$1
  
  echo &quot;Getting subscription ID&quot;
  SUBSCRIPTION_ID=$(az account show --query id --output tsv)
  echo &quot;Subscription ID is: $SUBSCRIPTION_ID&quot;
  
  echo &quot;Creating an App Registration and associated Service Principal&quot;
  SP=$(az ad sp create-for-rbac --role Contributor --name $APP_NAME --scopes /subscriptions/$SUBSCRIPTION_ID)
  
  echo &quot;The following is your Service Principal credentials, store them securely!&quot;
  echo $SP
  
  APP_ID=$(echo $SP | jq -r .appId)
  echo &quot;Application ID is: $APP_ID&quot;
  
  # Microsoft Graph API Id
  API_ID=&quot;00000003-0000-0000-c000-000000000000&quot;
  
  # IDs for various Application Roles
  echo &quot;Getting API permission IDs&quot;
  USER_READWRITE_ALL_ID=$(getPermissionId User.ReadWrite.All)
  GROUP_READWRITE_ALL_ID=$(getPermissionId Group.ReadWrite.All)
  APPLICATION_READWRITE_ALL_ID=$(getPermissionId Application.ReadWrite.All)
  
  # Add permissions to SP
  echo &quot;Adding API permissions to SP&quot;
  az ad app permission add \
    --id $APP_ID \
    --api $API_ID \
    --api-permissions \
        $USER_READWRITE_ALL_ID=Role \
        $GROUP_READWRITE_ALL_ID=Role \
        $APPLICATION_READWRITE_ALL_ID=Role
  
  echo &quot;Granting access for Microsoft Graph API&quot;
  az ad app permission grant --id $APP_ID --api $API_ID
  
  echo &quot;Granting admin-consent for API permissions&quot;
  az ad app permission admin-consent --id $APP_ID
  
  echo &quot;Done. Check out your SP at: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/$APP_ID&quot;
  </code></pre>