title: Assign an app-role to a managed-identity service principal
body: <p>Like demonstrated <a href="https://dev.to/ib1/protecting-azure-functions-with-api-management-service-53el" rel="nofollow noreferrer">here</a>, I want to secure an Azure Function app with AzureAD and only be able to call/invoke it from an Azure API Management instance (with system-assigned managed identity enabled). This works fine. However I really want to isolate access to the API (Functions app). As it stands now, ANY app in my tenant would be able to successfully authenticate and invoke the API. Therefore, I chose to enable <a href="https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/assign-user-or-group-access-portal#configure-an-application-to-require-user-assignment" rel="nofollow noreferrer">user-assignment</a> for that app registration.</p>
  <p>So basically, there is 1 API (Azure Functions) that is AzureAD protected. Then there is 1 service calling the API (Azure API Management). Without a role-assignment there is the following error message I can understand.</p>
  <pre><code>AADSTS501051: Application '&lt;appId&gt;'(&lt;name of APIM managed-identity&gt;) is not assigned to a role for the application '&lt;appId2&gt;'(&lt;name of app registration for the Azure Functions app's EasyAuth feature&gt;).
  </code></pre>
  <p>So I created an app role in the API's app registration. The normal guidance on how to assign such a role to an application can be found <strike>here</strike> <em>(EDIT: WRONG LINK SEE ANSWER)</em>. However this does only apply to the service principal manually created (read: not a MSI) because this requires the service principal can be found in the portal UI. This is not the case with anything related to a mangaged-identity.</p>
  <p>Since the above link also states that assignment can also be done using the <a href="https://docs.microsoft.com/en-us/graph/api/user-post-approleassignments?view=graph-rest-1.0&amp;tabs=http" rel="nofollow noreferrer">Graph API</a> I tried this as a workaround.</p>
  <pre class="lang-json prettyprint-override"><code>POST https://graph.microsoft.com/v1.0/users/{id}/appRoleAssignments
  Content-Type: application/json
  
  {
    &quot;principalId&quot;: &quot;principalId-value&quot;,
    &quot;resourceId&quot;: &quot;resourceId-value&quot;,
    &quot;appRoleId&quot;: &quot;appRoleId-value&quot;
  }
  </code></pre>
  <p>This does not work yielding the following error response (I have tried appId and objectId for id/principalId/resourceId):</p>
  <pre><code>&quot;Resource '&lt;guid of principalId&gt;' does not exist or one of its queried reference-property objects are not present.&quot;
  </code></pre>
  <p>Do you have any suggestions on what could be done? Any help is greatly appreciated.</p>