Skip to content

Instantly share code, notes, and snippets.

@jepetko
Last active December 21, 2020 11:51
Show Gist options
  • Save jepetko/bfe70ba44fc8d6c3af7f4285b85a56d2 to your computer and use it in GitHub Desktop.
Save jepetko/bfe70ba44fc8d6c3af7f4285b85a56d2 to your computer and use it in GitHub Desktop.
How to obtain access token for Graph API
import * as qs from 'querystring';
import 'isomorphic-fetch';
import {
AuthenticationHandler,
AuthenticationProviderOptions,
Client,
HTTPMessageHandler
} from '@microsoft/microsoft-graph-client';
export function getClient() {
const authProvider = {
getAccessToken: (authenticationProviderOptions?: AuthenticationProviderOptions): Promise<string> => {
const params = {
client_id: process.env.CLIENT_ID,
scope: 'https://graph.microsoft.com/.default',
client_secret: process.env.CLIENT_SECRET,
grant_type: 'client_credentials'
};
const body = qs.stringify(params);
return fetch(`https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/v2.0/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body
}).then(response => {
if (response.status >= 400) {
throw new Error(`Bad response from server: ${response.statusText}`);
}
return response.json();
}).then(body => {
return (body as unknown as {access_token: string}).access_token;
});
}
};
const authHandler = new AuthenticationHandler(authProvider);
const httpMessageHandler = new HTTPMessageHandler();
authHandler.setNext(httpMessageHandler);
return Client.initWithMiddleware({
defaultVersion: 'v1.0',
debugLogging: true,
middleware: authHandler,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment