Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@microsoft/microsoft-graph-client
Advanced tools
@microsoft/microsoft-graph-client is an npm package that provides a client library for accessing Microsoft Graph, which is a unified API endpoint for accessing data across Microsoft 365 services. This package allows developers to interact with various Microsoft services such as Outlook, OneDrive, and Azure Active Directory, among others.
Accessing User Information
This feature allows you to access information about the authenticated user. The code sample demonstrates how to initialize the client and make a request to the '/me' endpoint to retrieve user information.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
client.api('/me').get().then((user) => {
console.log(user);
}).catch((error) => {
console.error(error);
});
Sending an Email
This feature allows you to send an email using the Microsoft Graph API. The code sample demonstrates how to create an email message and send it using the '/me/sendMail' endpoint.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
const mail = {
message: {
subject: 'Hello from Microsoft Graph API',
body: {
contentType: 'Text',
content: 'This is a test email sent using Microsoft Graph API.'
},
toRecipients: [
{
emailAddress: {
address: 'recipient@example.com'
}
}
]
}
};
client.api('/me/sendMail').post({ message: mail }).then(() => {
console.log('Email sent successfully');
}).catch((error) => {
console.error(error);
});
Accessing OneDrive Files
This feature allows you to access files stored in OneDrive. The code sample demonstrates how to list the files in the root directory of the authenticated user's OneDrive using the '/me/drive/root/children' endpoint.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
client.api('/me/drive/root/children').get().then((files) => {
console.log(files);
}).catch((error) => {
console.error(error);
});
The 'msal' (Microsoft Authentication Library) package focuses on authentication and acquiring tokens for Microsoft services. While it does not provide direct access to Microsoft Graph endpoints, it is often used in conjunction with @microsoft/microsoft-graph-client to handle authentication.
The 'node-outlook' package is designed specifically for interacting with Outlook services. It provides functionalities for accessing mail, calendar, and contacts, similar to what @microsoft/microsoft-graph-client offers but is more focused on Outlook.
The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser.
Looking for IntelliSense on models (Users, Groups, etc.)? Check out the Microsoft Graph Types repository!
npm install @microsoft/microsoft-graph-client
import @microsoft/microsoft-graph-client
into your module.
import { Client } from "@microsoft/microsoft-graph-client";
Include lib/graph-js-sdk-web.js
in your page.
<script type="text/javascript" src="graph-js-sdk-web.js"></script>
Incase if your application ships with es6-promise and isomorphic-fetch just use lib/graph-js-sdk-core.js
<script type="text/javascript" src="graph-js-sdk-core.js"></script>
Register your application to use Microsoft Graph API using one of the following supported authentication portals:
The Microsoft Graph JavaScript Client Library has an adapter implementation (MSALAuthenticationProvider) for MSAL (Microsoft Authentication Library) which takes care of getting the accessToken
. MSAL library does not ship with this library, user has to include it externally (For including MSAL, refer this).
Note: MSAL is supported only for frontend applications, for server-side authentication you have to implement your own AuthenticationProvider. Refer implementing Custom Authentication Provider.
Refer devDependencies in package.json for the compatible msal version and update that version in below.
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>
const clientId = "your_client_id"; // Client Id of the registered application
const callback = (errorDesc, token, error, tokenType) => {};
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const options = {
redirectUri: "Your redirect URI",
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#initialization-of-msal
const userAgentApplication = new Msal.UserAgentApplication(clientId, undefined, callback, options);
const authProvider = new MicrosoftGraph.MSALAuthenticationProvider(userAgentApplication, graphScopes);
Refer devDependencies in package.json for the compatible msal version and update that version in below.
npm install msal@<version>
import { UserAgentApplication } from "msal";
import { MSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProvider";
const clientId = "your_client_id"; // Client Id of the registered application
const callback = (errorDesc, token, error, tokenType) => {};
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const options = {
redirectUri: "Your redirect URI",
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#initialization-of-msal
const userAgentApplication = new UserAgentApplication(clientId, undefined, callback, options);
const authProvider = new MSALAuthenticationProvider(userAgentApplication, scopes);
User can integrate own preferred authentication library by implementing IAuthenticationProvider
interface. Refer implementing Custom Authentication Provider.
An instance of the Client class handles requests to Microsoft Graph API and processing the responses. To create a new instance of this class, you need to provide an instance of IAuthenticationProvider
which needs to be passed as a value for authProvider
key in ClientOptions
to a static initializer method Client.initWithMiddleware
.
const options = {
authProvider, // An instance created from previous step
};
const Client = MicrosoftGraph.Client;
const client = Client.initWithMiddleware(options);
import { Client } from "@microsoft/microsoft-graph-client";
const options = {
authProvider, // An instance created from previous step
};
const client = Client.initWithMiddleware(options);
For more information on initializing client, refer this document.
Once you have authentication setup and an instance of Client, you can begin to make calls to the service. All requests should be start with client.api(path)
and end with an action.
Getting user details
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
Sending an email to the recipients
// Construct email object
const mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [
{
emailAddress: {
address: "example@example.com",
},
},
],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html",
},
};
try {
let response = await client.api("/me/sendMail").post({ message: mail });
console.log(response);
} catch (error) {
throw error;
}
For more information, refer: Calling Pattern, Actions, Query Params, API Methods and more.
We'd love to get your feedback about the Microsoft Graph JavaScript client library. You can send your questions and suggestions to us in the Issues section of this repository.
Please see the contributing guidelines.
See Third Party Notices for information on the packages that are included in the package.json
If you find a security issue with our libraries or services please report it to secure@microsoft.com with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
FAQs
Microsoft Graph Client Library
The npm package @microsoft/microsoft-graph-client receives a total of 339,969 weekly downloads. As such, @microsoft/microsoft-graph-client popularity was classified as popular.
We found that @microsoft/microsoft-graph-client demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.