Microsoft 365 Microsoft Graph

Microsoft Graph Mailbag – Microsoft Graph in Electron applications using Microsoft Graph Toolkit

In today’s Microsoft Graph Mailbag post, we’ll explain how to build a Microsoft Graph-powered Electron application. For authentication, we’ll use the Electron provider, an authentication provider in the Microsoft Graph Toolkit that’s built specifically for Electron.

This blog post covers the following:

  • Authenticating users in a new Electron app by using the Electron Provider
  • Adding content to the app and calling Microsoft Graph APIs using the authenticated client exposed by the Microsoft Graph Toolkit.

The Microsoft Graph Toolkit is a collection of reusable, framework-agnostic components, and authentication providers for accessing and working with Microsoft Graph. If you want to learn more about the Microsoft Graph Toolkit, see the A Lap around Microsoft Graph Toolkit blog series, and see the  Microsoft Graph Toolkit overview.

Please be sure to follow this blog series using https://aka.ms/MSGraphMailbag or with RSS using https://developer.microsoft.com/en-us/graph/blogs/feed/?tag=MSGraphMailbag.

Getting started

The Electron provider can be used to authenticate and access Microsoft Graph in an Electron application with just a few lines of code. In this post, we’ll build a   application that allows you to view and edit your to do tasks. You will also use the Electron provider for authentication and add some other Microsoft Graph Toolkit components to make your application look better.

There’s more! This app will also have a fun feature that changes your desktop wallpaper based on your presence status fetched from Microsoft Graph, just to give you that extra push of motivation to focus when you really need to!

Create an Electron app and add the Electron provider

This section will walk through the steps to create a simple Electron application. If you are new to Electron or want to learn more about the provider’s capabilities, such as caching tokens, see Electron provider.

First, clone the electron-quickstart-typescript repository on GitHub. We will be building on top of this boilerplate code.

git clone https://github.com/electron/electron-quick-start-typescript.git

Install all the necessary packages for this project.

npm install

Install the @microsoft/mgt-electron-provider and @microsoft/mgt-element npm packages as well. These will allow you to provide authentication for your app using MSAL and use the Microsoft Graph Toolkit components.

npm i @microsoft/mgt-element @microsoft/mgt-electron-provider

Install the ‘@microsoft/mgt-components’ package that contains all the Microsoft Graph-connected web components.

npm i @microsoft/mgt-components

Confirm that you can run the app:

npm start

Initializing the provider

To enable authentication on your app, you will need to initialize two classes: ElectronAuthenticator and ElectronProvider, in the main and renderer processes respectively. ElectronAuthenticator is responsible for setting up the configuration variables for MSAL authentication and acquiring access tokens. Because these tokens are needed by the components in the UI to call Microsoft Graph, we have an ElectronProvider (in the renderer process) that communicates with ElectronAuthenticator (in the main process) to request access tokens and receive information regarding signed in state.

Initialize the ElectronAuthenticator in the main process and set up the configuration variables such as client ID and required scopes.

First, open src/main.ts and import ElectronAuthenticator and MsalElectronConfig as follows:

import {
  ElectronAuthenticator,
  MsalElectronConfig,
} from '@microsoft/mgt-electron-provider/dist/Authenticator';

Next, add these lines of code in the createWindow() function to initialize the ElectronAuthenticator, right after where mainWindow is declared.

  • Replace <your_client_id> with the client ID from your app registration
  • mainWindow is the BrowserWindow instance that requires authentication
  • scopes is a list of all the scopes that are needed to render our MGT components as well as call the presence API
const config: MsalElectronConfig = {
clientId: '<your_client_id>',
mainWindow: mainWindow, //BrowserWindow instance that requires auth
scopes: [
'user.read',
'people.read',
'user.readbasic.all',
'contacts.read',
'presence.read.all',
'presence.read',
'user.read.all',
'calendars.read',
'Sites.Read.All',
'Sites.ReadWrite.All',
],
};
ElectronAuthenticator.initialize(config);

To initialize the ElectronProvider, add the following code to the src/renderer.ts file. In this code snippet, we’re also importing all the MGT components so we can use them in our HTML code.

And that’s it! Authentication, check!

Adding content and Microsoft Graph integrations

You can now use the Microsoft Graph Toolkit components in your index.html page and show the user’s To Do tasks. For this, we’re going to be using three toolkit components:

  • mgt-login (Facilitates authentication with a button to log in)
  • mgt-person (Shows details about the logged in user)
  • mgt-todo (Enables the user to add, remove, or edit tasks from Microsoft To Do)

Replace the content of the index.html page with the following.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>My To-Do App</title>
    <script type="module" src="./dist/renderer.js"></script>
  </head>
  <body>
    <mgt-login></mgt-login>
    <mgt-person person-query="me" show-presence view="twoLines" ></mgt-person>
    <mgt-todo group-by-day></mgt-todo>
  </body>
</html>

We are now done with the basic version of this app!

You can run the app with this command:

npm start

Your app should now look like:

That’s how simple it is to get started with the toolkit and Electron 😊.

Change your wallpaper based on presence data

Now for the fun part! Let’s enable this app to change the desktop wallpaper based on the user’s presence.

First, l install an npm package that makes it easy to change the desktop wallpaper:

npm install wallpaper

Now, our aim is to detect the state of the signed in user, and change the wallpaper based on their presence. This means we need to:

  1. Determine whether there is a signed in user.
  2. Call a function to get presence data and change the user’s wallpaper.

To determine whether a user is signed in, in the renderer process, subscribe to the onStateChanged event that is fired by the globalProvider whenever there is a change in the sign-in state.

Providers.globalProvider.onStateChanged(async (e) => {
  if (Providers.globalProvider.state === ProviderState.SignedIn) {
    checkPresence();
  }
});

Now, define your checkPresence() function.

For this, we need to call the presence API. One of my favorite things about the Microsoft Graph Toolkit is that it doesn’t restrict you to use only the existing components, but also provides you with an authenticated client that you can use to call any Microsoft Graph API you want, with just a few lines of code.

const presence = await Providers.globalProvider.graph
  .api('/me/presence')
  .get();

Now, we have our presence object. We recommend that you run console.log(presence) before the next step, just to know what the object looks like.

Let’s change the wallpaper in three situations. One, when the user’s presence is Do Not Disturb the other when it is Offline, and the last one for all others. We will need to use three different wallpapers.

Now, you may proceed to spend an embarrassing amount of time looking up stuff like “funny giraffe motivational wallpapers” ….No I didn’t do that :P.

Finally, let’s complete our checkPresence() function.

async function checkPresence() {
  setInterval(async function () {
    //Calling presence API to fetch presence data
    const presence = await Providers.globalProvider.graph
      .api('/me/presence')
      .get();

    if (presence.availability === 'DoNotDisturb') {
      await wallpaper.set(‘path-to-wallpaper1’);
    } else {
      if (presence.availability === 'Offline') {
        await wallpaper.set(‘path-to-wallpaper2’);
      } else {
        await wallpaper.set(path.join(‘path-to-wallpaper3’));
      }
    }
  }, 5000);
}

As you may have noticed, I have set an interval of 5 seconds which is how often the presence API will be queried.

We’re all done! Now you have an Electron application that you can sign in to and authenticate using the Electron provider, display your to-do tasks, and change your wallpaper based on your Teams status.

The working sample is on GitHub if you want to run it locally and check it out.

That’s all folks! The giraffe is right, I need to get back to work. See you next time!

 

Today’s post was written by Amrutha Srinivasan (Software Engineer on the Microsoft Graph Toolkit team).  You can follow Amrutha on LinkedIn. Join us for our next post on March 23, 2021.

filter-icon