この記事では、Microsoft Graph Toolkit を使用して Electron アプリを作成し、Microsoft 365 に接続する方法について説明します。 手順を完了すると、Microsoft 365 から現在サインインしているユーザーの予定を表示する Electron アプリが作成されます。
Electron アプリを作成する
Electron Forge を使用して新しい Electron アプリをスキャフォールディングします。 これにより、TypeScript に新しい Electron アプリが作成されます。これにより、より堅牢なコードを記述し、ランタイム エラーを回避できます。
npm init electron-app@latest mgt-app -- --template=webpack-typescript
作業ディレクトリを新しく作成したアプリに変更します。
cd mgt-app
アプリを実行できることを確認します。
npm start
ファイルを package.json
開き、電子開発の依存関係のバージョンが 28.2.4
であることを確認します。
28.2.4
は、 で必要な @microsoft/mgt-electron-provider
ピア依存関係の現在の最大バージョンです。
Microsoft Graph に接続されているすべての Web コンポーネントを含む '@microsoft/mgt-components' パッケージをインストールします。
npm i @microsoft/mgt-components
@microsoft/mgt-electron-provider
と @microsoft/mgt-element
npm パッケージもインストールします。 これにより、MSAL を使用してアプリの認証を提供し、Microsoft Graph Toolkit コンポーネントを使用できます。
npm i @microsoft/mgt-element @microsoft/mgt-electron-provider
アプリ/クライアント ID の作成
Microsoft Entra IDに新しいアプリケーション登録を追加してクライアント ID を取得する
Microsoft Entra IDでアプリケーションを作成するには、新しいアプリケーション登録を追加してから、アプリ名とリダイレクト URI を構成する必要があります。
Microsoft Entra IDでアプリを作成するには:
- Microsoft Entra 管理センターに移動します。
- [ID]> を展開し、[アプリケーション]> で [アプリの登録] を選択します。
- トップ メニューから、[新規登録] ボタンを選択します。
- アプリの名前を入力します。たとえば、
My Electron-App
です。 - サポートされているアカウントの種類については、[任意の組織のディレクトリ (任意のMicrosoft Entra ディレクトリ - マルチテナント)] と個人用 Microsoft アカウント (Skype、Xbox など) を選択します。
- [ リダイレクト URI ] フィールドのドロップダウンで、[ パブリック クライアント/ネイティブ (モバイル & デスクトップ)] を選択し、[URL] フィールドに「」と入力
msal://redirect
します。 - [登録] ボタンを選択して変更を確認します。
- アプリケーションの登録に移動します。
- 概要ページが表示されていることを確認します。
- [Essentials] セクションで、[アプリケーション (クライアント) ID] プロパティの値をコピーします。
Microsoft Graph Toolkit 認証プロバイダーを構成する
プリロード スクリプトで ContextBridge を初期化する
Electron v12 以降では、コンテキスト分離が既定で有効になっており、これはすべてのアプリケーションに推奨されるセキュリティ設定です。 コンテキストの分離では、開発者は ContextBridge を介してレンダラー プロセスで使用するために、メイン プロセスから API を明示的に公開する必要があります。 詳細については、「 Electron ドキュメントのコンテキスト分離」を参照してください。
src/preload.ts ファイルを開き、次のコードを追加します。
import { type IpcRendererEvent, contextBridge, ipcRenderer } from 'electron';
import { AuthenticationProviderOptions } from '@microsoft/microsoft-graph-client';
contextBridge.exposeInMainWorld("main", {
electronProvider: {
mgtAuthState: (callback: (event: IpcRendererEvent, authState: string) => void) => ipcRenderer.on('mgtAuthState', callback),
token: (options?: AuthenticationProviderOptions) => ipcRenderer.invoke('token', options),
login: () => ipcRenderer.invoke('login'),
logout: () => ipcRenderer.invoke('logout'),
approvedScopes: (callback: (event: IpcRendererEvent, scopes: string[]) => void) => ipcRenderer.on('approvedScopes', callback),
},
});
レンダラー プロセスでの ElectronContextBridgeProvider の初期化
はElectronContextBridgeProvider
、アクセス トークンを要求しElectronAuthenticator
、ツールキット コンポーネントが機能するために必要なサインイン状態に関する情報を受け取るために 、(メイン プロセスで) と通信する役割を担います。
アプリケーションで Microsoft Graph Toolkit コンポーネントを使用するには、開いているブラウザー ウィンドウに登録する必要があります。 これを行うには、使用するコンポーネントごとにレジスタ関数をインポートする必要があります。
を ElectronContextBridgeProvider
初期化して Microsoft Graph Toolkit コンポーネントを登録するには、 src/renderer.ts ファイルに次のコードを追加します。
import { Providers } from "@microsoft/mgt-element";
import { registerMgtAgendaComponent, registerMgtLoginComponent } from '@microsoft/mgt-components';
import {
type IContextBridgeImpl,
} from "@microsoft/mgt-electron-provider/dist/Provider";
import { ElectronContextBridgeProvider } from "@microsoft/mgt-electron-provider/dist/Provider/ElectronContextBridgeProvider";
// this provides typings for the object added to the renderer window by the preload script
declare global {
interface Window {
// can be named anything, like "electronApi"
main: {
electronProvider: IContextBridgeImpl;
};
}
}
// initialize the auth provider globally
const init = () => {
Providers.globalProvider = new ElectronContextBridgeProvider(window.main.electronProvider);
registerMgtLoginComponent();
registerMgtAgendaComponent();
};
init();
メイン プロセスでの ElectronAuthenticator の初期化
ElectronAuthenticator
は、MSAL 認証の構成変数の設定、アクセス トークンの取得、および との通信をElectronContextBridgeProvider
担当します。
ElectronAuthenticator
は、メイン プロセスで初期化され、クライアント ID や必要なスコープなどの構成変数を設定します。
まず、src/index.ts を開き、ページの上部から @microsoft/mgt-electron-provider
と をインポートElectronAuthenticator
MsalElectronConfig
します。
import {
ElectronAuthenticator,
MsalElectronConfig,
} from "@microsoft/mgt-electron-provider/dist/Authenticator";
次に、定数のインポートを追加します COMMON_AUTHORITY_URL
。
import { COMMON_AUTHORITY_URL } from '@microsoft/mgt-electron-provider/dist/Authenticator/Constants';
次に、関数にこれらのコード行を createWindow()
追加して、ここで mainWindow
宣言された直後に ElectronAuthenticator を初期化します。 をアプリ登録のクライアント ID に置き換えます <your_client_id>
。
const config: MsalElectronConfig = {
clientId: "<your_client_id>",
authority: COMMON_AUTHORITY_URL, // Uses the common auth endpoint
mainWindow: mainWindow, //This is the BrowserWindow instance that requires authentication
scopes: [
"user.read",
"user.read",
"people.read",
"user.readbasic.all",
"contacts.read",
"presence.read.all",
"presence.read",
"user.read.all",
"calendars.read",
],
};
ElectronAuthenticator.initialize(config);
開発コンテンツ セキュリティ ポリシーを追加する
Electron Forge スキャフォールディングするアプリケーションには、リモート サーバーからのデータのフェッチを禁止する既定のコンテンツ セキュリティ ポリシー (CSP) が含まれています。 開発目的で、非常に許容される CSP を追加できます。 運用アプリの場合は、悪意のあるアクターの攻撃面を減らしながらアプリケーションを機能させる堅牢な CSP を作成する必要があります。
forge.config.ts ファイルを開き、WebpackPlugin コンストラクターに渡されている既存の構成オブジェクトを次の構成オブジェクトに置き換えます。
{
mainConfig,
devContentSecurityPolicy: "default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;",
renderer: {
config: rendererConfig,
entryPoints: [
{
html: './src/index.html',
js: './src/renderer.ts',
name: 'main_window',
preload: {
js: './src/preload.ts',
},
},
],
},
}
HTML ページにコンポーネントを追加する
アプリにいくつかのコンテンツを追加します。 index.html ページで Microsoft Graph ツールキット コンポーネントを使用し、ユーザーの議題を表示できるようになりました。 index.html ページの内容を次のように置き換えます。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body>
<h1>❤️ Hello World! 🦒</h1>
<p>Welcome to your MGT Electron application.</p>
<mgt-login></mgt-login>
<mgt-agenda group-by-day></mgt-agenda>
</body>
</html>
アプリの実行
npm start
トークン キャッシュ機能をアプリに追加し、サイレント サインインを有効にする (詳細)
MSAL Node では、既定でメモリ内キャッシュがサポートされ、キャッシュのシリアル化を実行するための ICachePlugin インターフェイスが提供されますが、トークン キャッシュをディスクに格納する既定の方法は提供されません。 サイレント サインインまたはクロスプラットフォーム キャッシュを有効にするために永続キャッシュ ストレージが必要な場合は、MSAL Node によって提供される既定の実装を 拡張機能として使用することをお勧めします。 このプラグインをインポートし、初期化中にキャッシュ プラグインのインスタンスを ElectronAuthenticator
渡すことができます。
let config: MsalElectronConfig = {
...
cachePlugin: new PersistenceCachePlugin(filePersistence) //filePersistence is the instance of type IPersistence that you will need to create
};
これを実装する方法の詳細については、 Microsoft Authentication Library-for-js サンプルを参照してください。
関連コンテンツ
- プレイグラウンドでさまざまなコンポーネントを試してみてください。
- Microsoft Q&A について質問します。
- バグを報告するか、GitHub に機能リクエストを残してください。