how to get the access token from microsoft office 365 via nodejs
To get the access token from Microsoft Office 365 via Node.js, you can use the Microsoft Graph API and the MSAL (Microsoft Authentication Library) Node.js library.
Here are the steps:
-
Register an application in Azure Active Directory (AAD) and obtain the Application ID and Tenant ID.
-
Install the MSAL Node.js library:
npm install @azure/msal-node
- Create a configuration object with the following properties:
const config = {
auth: {
clientId: '<application-id>',
authority: 'https://login.microsoftonline.com/<tenant-id>',
clientSecret: '<client-secret>'
}
};
Replace <application-id>, <tenant-id>, and <client-secret> with your own values.
- Create an MSAL PublicClientApplication object:
const { PublicClientApplication } = require('@azure/msal-node');
const pca = new PublicClientApplication(config);
- Define the scopes you want to request access to:
const scopes = ['user.read', 'calendars.read'];
These scopes define the permissions the user needs to grant your application to access their data.
- Redirect the user to the authentication page:
const authCodeUrlParameters = {
scopes: scopes,
redirectUri: 'http://localhost:3000/redirect'
};
const authUrl = await pca.getAuthCodeUrl(authCodeUrlParameters);
Replace http://localhost:3000/redirect with your own redirect URI.
- Handle the authentication redirect:
const { AuthenticationResult } = require('@azure/msal-node');
const tokenRequest = {
code: '<authorization-code>',
scopes: scopes,
redirectUri: 'http://localhost:3000/redirect'
};
const response = await pca.acquireTokenByCode(tokenRequest);
const token = response.accessToken;
Replace <authorization-code> with the code obtained from the redirect URI.
The acquireTokenByCode method will exchange the authorization code for an access token.
- Use the access token to make requests to the Microsoft Graph API:
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, token);
}
});
const events = await client.api('/me/events').get();
console.log(events);
This example uses the Microsoft Graph API to get the user's calendar events.
That's it! You should now be able to get the access token from Microsoft Office 365 via Node.js.
原文地址: https://www.cveoy.top/t/topic/FxZ 著作权归作者所有。请勿转载和采集!