{"id":305,"date":"2021-03-16T10:50:37","date_gmt":"2021-03-16T17:50:37","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/?p=305"},"modified":"2021-03-16T09:43:35","modified_gmt":"2021-03-16T16:43:35","slug":"leverage-microsoft-graph-in-electron-applications-using-microsoft-graph-toolkit","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/leverage-microsoft-graph-in-electron-applications-using-microsoft-graph-toolkit\/","title":{"rendered":"Leverage Microsoft Graph in Electron Applications using Microsoft Graph Toolkit!"},"content":{"rendered":"<p><span style=\"font-size: 18pt;\"><strong>Electron and Microsoft Graph<\/strong><\/span><\/p>\n<p><a href=\"https:\/\/www.electronjs.org\/\">Electron<\/a> is a framework for creating native desktop applications with web technologies like JavaScript, HTML, and CSS. It has become a popular development platform for native applications and is seeing increasing adoption on Windows. Some of the popular applications on Windows, such as Microsoft Teams, VS Code and Slack are in fact Electron Applications!<\/p>\n<p><a href=\"https:\/\/developer.microsoft.com\/en-us\/graph\">Microsoft Graph<\/a> enables developers to tap into the tremendous amount of data in Microsoft 365 to create rich, user-centric and intelligent app experiences. It provides an API endpoint to all kinds of data related to the user, such as the people they work with, files they recently opened, their agenda, and more that can easily boost user productivity in your application. For example, you can use the Microsoft Graph API to access your calendar, and find the best time for your next meeting, and schedule it too. Neat, right?<\/p>\n<p>To learn more about how you can use Microsoft Graph in your application, visit their <a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/overview#what-can-you-do-with-microsoft-graph\">documentation<\/a> or play around with the Graph APIs in the <a href=\"https:\/\/developer.microsoft.com\/en-us\/graph\/graph-explorer\">Graph Explorer<\/a>.<img decoding=\"async\" style=\"font-size: 1rem;\" src=\"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-content\/uploads\/sites\/61\/2021\/03\/mgt2Belectron2.png\" alt=\"Microsoft Graph Toolkit and Electron\" \/><\/p>\n<p><span style=\"font-size: 12pt;\">Today, we will be\u00a0bringing these two amazing technologies together and build a Microsoft Graph powered Electron application. For authentication, we will be using the Electron provider, an auth provider part of the Microsoft Graph toolkit built specifically for Electron. This blog post will cover the following sections:<\/span><\/p>\n<ul>\n<li><span style=\"font-size: 12pt;\">Authenticating users in a new Electron app by using the Electron Provider<\/span><\/li>\n<li><span style=\"font-size: 12pt;\">Adding content to the app and calling Microsoft Graph API\u2019s using the Graph toolkit.<\/span><\/li>\n<\/ul>\n<h2><span style=\"font-size: 18pt;\">Getting Started<\/span><\/h2>\n<p>The Microsoft Graph Toolkit (MGT) 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, I suggest visiting a blog series called <a href=\"http:\/\/aka.ms\/mgtlap\">A Lap around Microsoft Graph Toolkit<\/a> and then checking out our <a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/overview\">documentation<\/a>.<\/p>\n<p>The Electron Provider can be used to authenticate with Microsoft Identity and access Microsoft Graph in an Electron application with just a few lines of code. In this blogpost, we will build a <a href=\"https:\/\/todo.microsoft.com\/tasks\/\">To-Do<\/a> application that allows you to view and edit your to-do\u2019s. You will also use the Electron provider for authentication and add some other MGT (Microsoft Graph Toolkit) components to make your application look better.<\/p>\n<p>And&#8230;..there&#8217;s more! This app will also have a fun feature that changes your desktop wallpaper based on your presence status fetched from the Graph, just to give you that extra push of motivation to focus when you really need to!<\/p>\n<p>Let&#8217;s get started&#8230;<\/p>\n<h2><span style=\"font-size: 18pt;\">Create an Electron app and add the Electron provider<\/span><\/h2>\n<p>The following 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\u2019s capabilities such as caching tokens, I recommend that you follow the <a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/get-started\/build-an-electron-app\">Getting Started<\/a> guide in our documentation. You can then come back here for the later sections.<\/p>\n<p>First, let\u2019s clone the <a href=\"https:\/\/github.com\/electron\/electron-quick-start-typescript\">electron-quickstart-typescript<\/a> repository on GitHub. We will be building on top of this boilerplate code.<\/p>\n<pre><code class=\"cmd\">git clone https:\/\/github.com\/electron\/electron-quick-start-typescript.git<\/code><\/pre>\n<p>Navigate to the project folder.<\/p>\n<pre class=\"prettyprint\">cd electron-quick-start-typescript<\/pre>\n<p>Install all the necessary packages for this project.<\/p>\n<pre><code class=\"cmd\">npm install\r\n<\/code><\/pre>\n<p>Next, install the <code>@microsoft\/mgt-electron-provider<\/code> and <code>@microsoft\/mgt-element<\/code> npm packages as well. These will allow you to provide authentication for your app using MSAL and use the Microsoft Graph Toolkit components.<\/p>\n<pre><code class=\"cmd\">npm i @microsoft\/mgt-element @microsoft\/mgt-electron-provider\r\n<\/code><\/pre>\n<p>Next, install the <code>@microsoft\/mgt-components<\/code> package that contains all the Microsoft Graph-connected web components.<code class=\"cmd\"><\/code><code>\n<\/code><\/p>\n<pre class=\"prettyprint\">npm i @microsoft\/mgt-components<\/pre>\n<p>Finally, confirm that you can run the app:<\/p>\n<pre class=\"prettyprint\">npm start<\/pre>\n<h2><span style=\"font-size: 18pt;\">Initializing the provider<\/span><\/h2>\n<p>To enable authentication on your app, you will need to initialize two classes: <em>ElectronAuthenticator<\/em> and <em>ElectronProvider,<\/em> in the main and renderer processes respectively.<\/p>\n<p>What do <em>ElectronAuthenticator<\/em> and <em>ElectronProvider<\/em> do?<\/p>\n<ul>\n<li><em>ElectronAuthenticator<\/em> is responsible for setting up the configuration variables for <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/active-directory\/develop\/msal-overview\">MSAL<\/a> authentication and acquiring access tokens.<\/li>\n<li>Since these tokens are needed by the components in the UI to call Microsoft Graph, we have an <em>ElectronProvider<\/em> (in the renderer process) that communicates with <em>ElectronAuthenticator<\/em> (in the main process) to request access tokens and receive information regarding signed in state.<\/li>\n<\/ul>\n<p>Let&#8217;s go ahead and initialize the <em>ElectronAuthenticator<\/em> in the main process and set up the configuration variables such as client ID and required scopes.<\/p>\n<p>First, open <em>src\/main.ts<\/em> and import <em>ElectronAuthenticator<\/em> and <em>MsalElectronConfig<\/em> as follows:<\/p>\n<pre><code class=\"tsx\">import {\r\n ElectronAuthenticator,\r\n MsalElectronConfig,\r\n} from '@microsoft\/mgt-electron-provider\/dist\/Authenticator';\r\n<\/code><\/pre>\n<p>Next, add these lines of code in the <em>createWindow()<\/em> function to initialize the <em>ElectronAuthenticator<\/em>, right after where <em>mainWindow<\/em> is declared.<\/p>\n<ul>\n<li>Replace with the client ID from your <a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/providers\/electron#add-new-application-registration-in-azure-active-directory-to-get-a-client-id\">app registration<\/a>.<\/li>\n<li><em>mainWindow<\/em> is the BrowserWindow instance that requires authentication<\/li>\n<li><em>scopes<\/em> is a list of all the scopes that are needed to render our MGT components as well as call the presence API.<\/li>\n<\/ul>\n<pre><code class=\"tsx\">const config: MsalElectronConfig = {\r\n    clientId: '&lt;your_client_id&gt;',\r\n    mainWindow: mainWindow, \/\/BrowserWindow instance that requires auth\r\n    scopes: [\r\n      'user.read',\r\n      'people.read',\r\n      'user.readbasic.all',\r\n      'contacts.read',\r\n      'presence.read.all',\r\n      'presence.read',\r\n      'user.read.all',\r\n      'calendars.read',\r\n      'Sites.Read.All',\r\n      'Sites.ReadWrite.All',\r\n    ],\r\n  };\r\n  ElectronAuthenticator.initialize(config);\r\n<\/code><\/pre>\n<p>To initialize the <em>ElectronProvider<\/em>, add the following code to the src\/renderer.ts file. In this code snippet, we are also importing all the mgt components so we can use them in our html code.<\/p>\n<pre><code class=\"tsx\">import { Providers, ProviderState } from '@microsoft\/mgt-element';\r\nimport { ElectronProvider } from '@microsoft\/mgt-electron-provider\/dist\/Provider';\r\nimport '@microsoft\/mgt-components';\r\n\r\n\/\/ initialize the auth provider globally\r\nProviders.globalProvider = new ElectronProvider();\r\n<\/code><\/pre>\n<p>And that\u2019s it! Authentication, check!<\/p>\n<h2><span style=\"font-size: 18pt;\">Adding content and Graph Integrations<\/span><\/h2>\n<p>You can now use the Microsoft Graph Toolkit components in your <em>index.html<\/em> page and show the user&#8217;s To Do tasks. For this, we are going to be using 3 MGT components:<\/p>\n<ul>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/components\/login\">mgt-login<\/a> (Facilitates authentication with a button to log in),<\/li>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/components\/person\">mgt-person<\/a> (Shows details about the logged in user) and<\/li>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/components\/todo\">mgt-todo<\/a> (Enables the user to add, remove or edit tasks from Microsoft To Do)<\/li>\n<\/ul>\n<p>Replace the content of the <em>index.html<\/em> page with the following.<\/p>\n<pre><code class=\"html\">&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n &lt;head&gt;\r\n   &lt;meta charset=\"UTF-8\" \/&gt;\r\n   &lt;title&gt;My To-Do App&lt;\/title&gt;\r\n   &lt;script type=\"module\" src=\".\/dist\/renderer.js\"&gt;&lt;\/script&gt;\r\n &lt;\/head&gt;\r\n &lt;body&gt;\r\n   &lt;mgt-login&gt;&lt;\/mgt-login&gt;\r\n   &lt;mgt-person person-query=\"me\" show-presence view=\"twoLines\" &gt;&lt;\/mgt-person&gt;\r\n   &lt;mgt-todo group-by-day&gt;&lt;\/mgt-todo&gt;\r\n &lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/code><\/pre>\n<p>We are now done with the basic version of this app!<\/p>\n<p>You can now run the app with this command:<\/p>\n<pre><code class=\"cmd\">npm start\r\n<\/code><\/pre>\n<p>Your app should now look like this (play the GIF if it does not autoplay):<\/p>\n<p><img decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-content\/uploads\/sites\/61\/2021\/03\/app1.gif\" alt=\"Simple Electron App with Graph Authentication\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>That\u2019s how simple it is to get started with the Microsoft Graph Toolkit on Electron \ud83d\ude0a<\/p>\n<h2><span style=\"font-size: 18pt;\">Change your wallpaper based on Presence data<\/span><\/h2>\n<p>Now for the fun part! Let\u2019s enable this app to change the desktop wallpaper based on the user\u2019s presence.<\/p>\n<p>First, let\u2019s install an npm <a href=\"https:\/\/www.npmjs.com\/package\/wallpaper\">package<\/a> that makes it easy to change the desktop wallpaper:<\/p>\n<pre><code class=\"cmd\">npm install wallpaper\r\n<\/code><\/pre>\n<p>Now, our aim is to detect the state of the logged in user, and change the wallpaper based on their presence. This means we need to:<\/p>\n<ul>\n<li>Check if there is a logged in user, and<\/li>\n<li>Call a function to get presence data and change the user\u2019s wallpaper.<\/li>\n<\/ul>\n<p>To check if a user is logged in, in the renderer process, simply subscribe to the \u201c<em>onStateChanged<\/em>\u201d event that is fired by the <em>globalProvider<\/em> whenever there is a change in the logged in or logged out state.<\/p>\n<pre><code class=\"tsx\">Providers.globalProvider.onStateChanged(async (e) =&gt; {\r\n  if (Providers.globalProvider.state === ProviderState.SignedIn) {\r\n    checkPresence();\r\n  }\r\n});\r\n<\/code><\/pre>\n<p>Now, we have our presence object. I&#8217;d recommend that you run console.log(presence) before the next step, just to know what the object looks like.<\/p>\n<p>Let\u2019s change the wallpaper in three situations. One, when the user\u2019s 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.<\/p>\n<p>You may now proceed to spend an embarrassing amount of time looking up stuff like \u201cfunny giraffe motivational wallpapers\u201d \u2026.No I didn\u2019t do that :P.<\/p>\n<p>Finally, let\u2019s complete our checkPresence() function.<\/p>\n<pre><code class=\"tsx\">async function checkPresence() {\r\n  setInterval(async function () {\r\n    \/\/Calling presence API to fetch presence data\r\n    const presence = await Providers.globalProvider.graph\r\n      .api('\/me\/presence')\r\n      .get();\r\n\r\n    if (presence.availability === 'DoNotDisturb') {\r\n      await wallpaper.set(\u2018path-to-wallpaper1\u2019);\r\n    } else {\r\n      if (presence.availability === 'Offline') {\r\n        await wallpaper.set(\u2018path-to-wallpaper2\u2019);\r\n      } else {\r\n        await wallpaper.set(path.join(\u2018path-to-wallpaper3\u2019));\r\n      }\r\n    }\r\n  }, 5000);\r\n}\r\n<\/code><\/pre>\n<p>As you may have noticed, I have set an interval of 5 seconds which is how often the presence API will be queried.<\/p>\n<p>We\u2019re 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.<\/p>\n<p style=\"text-align: center;\">\u00a0 <iframe class=\"giphy-embed\" src=\"https:\/\/giphy.com\/embed\/SC4cp2mvIbQa1fSQsU\" width=\"480\" height=\"270\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\" data-mce-fragment=\"1\"><\/iframe><span style=\"font-size: 8pt;\"><a href=\"https:\/\/giphy.com\/gifs\/SC4cp2mvIbQa1fSQsU\">(via GIPHY)<\/a><\/span><\/p>\n<p>&nbsp;<\/p>\n<p>The working sample is on <a href=\"https:\/\/github.com\/amrutha95\/Mgt-Electron-Provider-Demo\">GitHub<\/a> if you want to run it locally and check it out.<\/p>\n<p>Here are some links to learn more about Microsoft Graph Toolkit and the Electron Provider:<\/p>\n<ul>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/providers\/electron\">Electron provider documentation<\/a><\/li>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/graph\/toolkit\/overview\">Microsoft Graph Toolkit Overview and Documentation<\/a><\/li>\n<li><a href=\"https:\/\/mgt.dev\/\">Toolkit Playground<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/microsoftgraph\/microsoft-graph-toolkit\">Microsoft Graph Toolkit GitHub repository<\/a><\/li>\n<\/ul>\n<p>That\u2019s all folks! The giraffe is right, I need to get back to work. See you next time!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Microsoft Graph Toolkit recently released an Authentication provider specifically for Electron applications that allows authentication and Graph integration with very few lines of code. This post walks you through the process of building a Graph powered Electron application using the Microsoft Graph Toolkit.<\/p>\n","protected":false},"author":54489,"featured_media":208,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[32,31,25,27,33],"class_list":["post-305","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ifdef-windows","tag-authentication","tag-electron","tag-mgt","tag-microsoft-graph-toolkit","tag-msal"],"acf":[],"blog_post_summary":"<p>The Microsoft Graph Toolkit recently released an Authentication provider specifically for Electron applications that allows authentication and Graph integration with very few lines of code. This post walks you through the process of building a Graph powered Electron application using the Microsoft Graph Toolkit.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/posts\/305","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/users\/54489"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/comments?post=305"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/posts\/305\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/media\/208"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/media?parent=305"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/categories?post=305"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/ifdef-windows\/wp-json\/wp\/v2\/tags?post=305"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}