Search code examples
office365office365apimicrosoft-graph-apioffice365-restapi

Microsoft Graph fails to list directory files


When trying to list directory items for "me" in microsoft graph I get 400 Bad Request with the following error: "Missing necessary user claims."

Steps to reproduce:

  1. Create application via Application Registration Tool , give permission to Files.Read
  2. Use create Client ID and Client Secret to get a token (following their guide) cURL:

    curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=client_credentials&client_id=<client-id>&client_secret=<client-secret>=&resource=https://graph.microsoft.com' "https://login.microsoftonline.com/<my-tenant-id>/oauth2/token"

  3. Use created <Access-Token> to make a request to list root directory like (cURL):

    curl -X GET -H "Authorization: Bearer <Access-Token>" -H "Cache-Control: no-cache" "https://graph.microsoft.com/v1.0/me/drive/root/children"

Get response:

400 Bad Request  
{
  "error": {
    "code": "BadRequest",
    "message": "Missing necessary user claims.",
    "innerError": {
      "request-id": "36c384f4-1810-4d96-ad69-d69a67d11ece",
      "date": "2016-05-31T14:39:05"
    }
  }
}

Any help would be greatly appreciated


Solution

  • In your example, you are only authenticating the application (known as "app-only authentication", or, in reference to the OAuth 2.0 flow, as the "Client Credentials Grant" flow). However, your request specifically makes reference to a user (.../me/...), i.e., you.

    The most common (and most complete) way to authenticate and authorize a user is to invoke the Authorization Code Grant flow to obtain an access token that is for both the app and the user. The access token obtained at the end of this flow will include claims about the signed-in user, and allow Microsoft Graph to know who you are referring to by "me". From the docs:

    To get your app authorized, you must get the user authenticated first. You do this by redirecting the user to the Azure Active Directory (Azure AD) authorization endpoint, along with your app information, to sign in to their Office 365 account. Once the user is signed in, and consents to the permissions requested by your app (if the user has not done so already), your app will receive an authorization code required to acquire an OAuth access token.

    Some more reading: