Skip to content

Instantly share code, notes, and snippets.

@saostad
Last active March 11, 2021 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saostad/a25e59402cdaecd6b26200e1c1ca1e39 to your computer and use it in GitHub Desktop.
Save saostad/a25e59402cdaecd6b26200e1c1ca1e39 to your computer and use it in GitHub Desktop.
get Azure graph token by custom authentication provider by client_id and client_secret
import { Client } from "@microsoft/microsoft-graph-client";
import { MyAuthenticationProvider } from "./MyAuthenticationProvider";
const clientOptions = {
authProvider: new MyAuthenticationProvider(),
};
const client = Client.initWithMiddleware(clientOptions);
import { AuthenticationProvider } from "@microsoft/microsoft-graph-client";
const axios = require("axios").default;
const qs = require("qs");
const msGraph_AuthUrl = process.env.msGraph_AuthUrl;
const msGraph_client_id = process.env.msGraph_client_id;
const msGraph_client_secret = process.env.msGraph_client_secret;
const msGraph_tenant_id = process.env.msGraph_tenant_id;
export class MyAuthenticationProvider implements AuthenticationProvider {
/**
* This method will get called before every request to the msgraph server
* This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
* Basically this method will contain the implementation for getting and refreshing accessTokens
*/
public async getAccessToken(): Promise<string> {
let data = qs.stringify({
client_id: msGraph_client_id,
client_secret: msGraph_client_secret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials",
});
let config = {
method: "post",
url: `${msGraph_AuthUrl}/${msGraph_tenant_id}/oauth2/v2.0/token`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
};
let response = await axios(config)
.then(function (resp: any) {
console.log("Token Received");
return resp.data.access_token;
})
.catch(function (error: any) {
console.log(error);
});
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment