1

After following the instruction from the question given in

How to get Microsoft Graph API Access token from Node Script?

I am using React with node/express for this and i am following a tutorial from

https://jscomplete.com/learn/1rd-reactful

my code/server.js is as follows,

import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../components/App';


const server = express();
server.use(express.static('dist'));

server.get('/', (req, res) => {
  const initialMarkup = ReactDOMServer.renderToString(<App />);

  res.send(`
    <html>
      <head>
        <title>Sample React App</title>
      </head>
      <body>
        <div id="mountNode">${initialMarkup}</div>
        <script src="/main.js"></script>
      </body>
    </html>
  `)
});



const request = require("request");

const endpoint = "https://login.microsoftonline.com/[My Tenant].onmicrosoft.com/oauth2/token";
const requestParams = {
    grant_type: "client_credentials",
    client_id: "[My ApplicationID]",
    client_secret: "[My Secret]",
    resource: "https://graph.windows.net"
};


request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
    if (err) {
        console.log("error");
    }
    else {
        console.log("Body=" + body);
        let parsedBody = JSON.parse(body);         
        if (parsedBody.error_description) {
            console.log("Error=" + parsedBody.error_description);
        }
        else {
            console.log("Access Token=" + parsedBody.access_token);
            testGraphAPI(parsedBody.access_token);
        }
    }
});

function testGraphAPI(accessToken) {
    request.get({
        url:"https://graph.microsoft.com/v1.0/users",
        headers: {
          "Authorization": "Bearer " + accessToken
        }
    }, function(err, response, body) {
        console.log(body);
    })
}


server.listen(4242, () => console.log('Server is running...'));

I am getting the access token fine but i am getting an error when i run the function testGraphAPI(accessToken) to test it. It says

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "request-id": "4abe8022-ebf8-4ae7-b9be-8dd01a460eeb",
      "date": "2019-09-28T08:21:07"
    }
  }
}

I have also kept my redirect url in active directory as http://localhost:4242/

Can someone please give me suggestions on how to fix this, because i need to use the access token for further work.

bheadr92
  • 33
  • 1
  • 5

0 Answers0