Tuesday 16 May 2017

Calling Microsoft Graph API from inside Azure Functions

I'm trying to write a simple Azure Function that calls the Microsoft Graph API. But I could not make the access_token work. Here is what I've done:

  1. Created a new Azure Function App from the Azure Portal
  2. Turned on the "App Service Authentication" setting and instructed it to sign in with AAD (management mode is Express).
  3. Configured the app to have delegated permissions like "Sign in and read user profile" for Microsoft Graph.
  4. Created a new JavaScript function HttpTriggerJS1
  5. Changed the authorization level of this function to "Anonymous" (otherwise by default the "Function" level would not even allow me to run the function, always returning 401 Unauthorized)
  6. Installed the necessary Node module (npm install request)
  7. And the actual function:

    var request = require('request');
    module.exports = function (context, req) {
        var token = req.headers['x-ms-token-aad-access-token'];
        var reqUrl = 'https://graph.microsoft.com/v1.0/me/';
        request.get(reqUrl, {'auth': {'bearer': token}}, function (err, response, msg) {
            context.res = {
                body: msg
            };
            context.done();
        });
    };
    
    
  8. Tested this function in a separate browser window. Signed me in to AAD correctly.

  9. But the message returned from Graph was:

    "{
      "error": {
        "code": "InvalidAuthenticationToken",
        "message": "CompactToken parsing failed with error code: -2147184105",
        "innerError": {
          "request-id": "4c78551d-f0fe-4104-b1d3-e2d96fd3c02c",
          "date": "2017-05-16T19:11:14"
        }
      }
    }"
    
    

I looked into the token I got from req.headers['x-ms-token-aad-access-token']. It's something like "AQABAA....", which seems different from the regular access_token I've seen before that starts with "eyJ....".

What could be wrong here? When calling the Graph API, am I supposed to be using the access_token from the request headers?

Thanks!



via Tony Blues

No comments:

Post a Comment