Skip to content

Instantly share code, notes, and snippets.

@icchan
Last active February 8, 2019 03:06
Show Gist options
  • Save icchan/6f341625cde0c3bdee8b728f9df62345 to your computer and use it in GitHub Desktop.
Save icchan/6f341625cde0c3bdee8b728f9df62345 to your computer and use it in GitHub Desktop.
Sample Node for obtaining an application token to call Microsoft Graph API
var request = require('request');
const MicrosoftGraph = require("@microsoft/microsoft-graph-client");
// required inputs
var tenant = ''; // tenant id
var clientId = ''; // application id
var secret = ''; // application password
// prepare http request
var url = 'https://login.microsoftonline.com/' + tenant + '/oauth2/v2.0/token';
var body = 'grant_type=client_credentials&client_id=' + clientId + '&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=' + secret
const options = {
url: url,
body: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
// Call the token API to get a token
request(options, handler);
// handle response and call graph
var handler = function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
var token = json.access_token;
// TODO here you can do something with the token
// e.g. test the token by calling graph api
callGraphApi(token);
} else {
console.log(body);
}
}
// make a call to graph to test the access token
var callGraphApi = function (token) {
// Initialize Graph client
const client = MicrosoftGraph.Client.init({
defaultVersion: 'v1.0',
debugLogging: true,
authProvider: (done) => {
done(null, token);
}
});
// get sharepoint root
client
.api('/sites/root')
.get()
.then((res) => {
console.log(res);
}).catch((res) => {
console.log(res);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment