Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix auth MS Graph React sample #750

Merged
merged 10 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions Samples/auth/Office-Add-in-Microsoft-Graph-React/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ Integrating data from online service providers increases the value and adoption

To run this code sample, the following are required.

* [Node and npm](https://nodejs.org/en/), version 10.15.3 or later (npm version 6.2.0 or later). The sample was not tested on earlier versions, but may work with them.
* [Node and npm](https://nodejs.org/en/), version 18.20.2 or later (npm version 10.5.0 or later).

* TypeScript version 3.1.6 or later. The sample was not tested on earlier versions, but may work with them.
* TypeScript version 5.4.3 or later.

* A Microsoft 365 account. You can get one if you qualify for a Microsoft 365 E5 developer subscription through the [Microsoft 365 Developer Program](https://aka.ms/m365devprogram); for details, see the [FAQ](https://learn.microsoft.com/office/developer-program/microsoft-365-developer-program-faq#who-qualifies-for-a-microsoft-365-e5-developer-subscription-). Alternatively, you can [sign up for a 1-month free trial](https://www.microsoft.com/microsoft-365/try) or [purchase a Microsoft 365 plan](https://www.microsoft.com/microsoft-365/business/compare-all-microsoft-365-business-products-g).

Expand All @@ -71,10 +71,7 @@ Version | Date | Comments
1.1 | December 10th, 2020 | Upgrade MSAL.js to v2
1.0 | August 29th, 2019| Initial release
1.1 | January 14th, 2021| Changed system for creating and installing the SSL certificates for HTTPS.

## Disclaimer

**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
1.2 | April 4th, 2024 | Updated to MSAL 3.7.1. Refactored code.

----------

Expand All @@ -87,7 +84,7 @@ Version | Date | Comments
1. Select **New registration**. On the **Register an application** page, set the values as follows.

* Set **Name** to `ExcelGraphDemo`.
* Set **Supported account types** to **Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)**.
* Set **Supported account types** to **Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)**.
* In the **Redirect URI** section, ensure that **Single-page application (SPA)** is selected in the drop down and then set the URI to `https://localhost:3000/login/login.html`.
* Select **Register**.

Expand All @@ -100,6 +97,7 @@ Version | Date | Comments
### Configure the sample
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved

1. In a code editor, open the `/login/login.ts` file in the project. Near the top is a configuration property called `clientId`. Replace the `YOUR APP ID HERE` placeholder value with the application ID you copied in the previous step. Save and close the file.
1. Open the `/logout/logout.ts` file in the project. Near the top is a configuration property called `clientId`. Replace the `YOUR APP ID HERE` placeholder value with the application ID you copied in the previous step. Save and close the file.
1. Open a **Command Prompt** *as an administrator*.
1. Navigate to the root of the sample, which would normally be `[PATH-TO-YOUR-PROJECTS]\Office-Add-in-samples\Samples\auth\Office-Add-in-Microsoft-Graph-React`.
1. Run the command `npm install`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ const fs = require('fs');
const path = require('path');
const os = require('os');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');

// homedir() gets the user's home folder for the OS.
// E.g., 'c:\users\[USERNAME]' for Windows or '/users/[USERNAME]' for Mac
const certPath = os.homedir() + '/.office-addin-dev-certs/';

module.exports = webpackMerge(commonConfig, {
module.exports = merge(commonConfig, {
devtool: 'eval-source-map',
devServer: {
client: {
Expand All @@ -22,11 +22,13 @@ module.exports = webpackMerge(commonConfig, {
directory: path.resolve('dist'),
publicPath: '/'
},
hot: true,
https: {
key: fs.readFileSync(certPath + 'localhost.key'),
cert: fs.readFileSync(certPath + 'localhost.crt'),
cacert: fs.readFileSync(certPath + 'ca.crt')
server: {
type: 'https',
options: {
cert: certPath + 'localhost.crt',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

usually use path.resolve for paths

cacert: certPath + 'ca.crt',
key: certPath + 'localhost.key'
}
},
compress: true,
port: 3000,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
module.exports = merge(commonConfig, {
devtool: 'source-map',

performance: {
Expand All @@ -12,6 +12,6 @@ module.exports = webpackMerge(commonConfig, {

optimization: {
minimize: true
}
}
});

65 changes: 31 additions & 34 deletions Samples/auth/Office-Add-in-Microsoft-Graph-React/login/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,37 @@

import { PublicClientApplication } from "@azure/msal-browser";

(() => {
// The initialize function must be run each time a new page is loaded
Office.initialize = () => {
Office.onReady(async () => {
const pca = new PublicClientApplication({
auth: {
clientId: 'YOUR APP ID HERE',
authority: 'https://login.microsoftonline.com/common',
redirectUri: `${window.location.origin}/login/login.html` // Must be registered as "spa" type.
},
cache: {
cacheLocation: 'localStorage' // Needed to avoid a "login required" error.
}
});
await pca.initialize();

const msalInstance = new PublicClientApplication({
auth: {
clientId: 'YOUR APP ID HERE',
authority: 'https://login.microsoftonline.com/common',
redirectUri: 'https://localhost:3000/login/login.html' // Must be registered as "spa" type
},
cache: {
cacheLocation: 'localStorage', // needed to avoid "login required" error
storeAuthStateInCookie: true // recommended to avoid certain IE/Edge issues
}
try {
// handleRedirectPromise should be invoked on every page load.
const response = await pca.handleRedirectPromise();
if (response) {
Office.context.ui.messageParent(JSON.stringify({ status: 'success', token: response.accessToken, userName: response.account.username}));
} else {
// A problem occurred, so invoke login.
await pca.loginRedirect({
scopes: ['user.read', 'files.read.all']
});
}
} catch (error) {
const errorData = {
errorMessage: error.errorCode,
message: error.errorMessage,
errorCode: error.stack
};
Office.context.ui.messageParent(JSON.stringify({ status: 'failure', result: errorData }));
}
});

// handleRedirectPromise should be invoked on every page load
msalInstance.handleRedirectPromise()
.then((response) => {
// If response is non-null, it means page is returning from AAD with a successful response
if (response) {
Office.context.ui.messageParent( JSON.stringify({ status: 'success', result : response.accessToken }) );
} else {
// Otherwise, invoke login
msalInstance.loginRedirect({
scopes: ['user.read', 'files.read.all']
});
}
})
.catch((error) => {
const errorData: string = `errorMessage: ${error.errorCode}
message: ${error.errorMessage}
errorCode: ${error.stack}`;
Office.context.ui.messageParent( JSON.stringify({ status: 'failure', result: errorData }));
});
};
})();
40 changes: 28 additions & 12 deletions Samples/auth/Office-Add-in-Microsoft-Graph-React/logout/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,34 @@

import { PublicClientApplication } from '@azure/msal-browser';

(() => {
// The initialize function must be run each time a new page is loaded
Office.initialize = () => {
let pca;

const msalInstance = new PublicClientApplication({
auth: {
clientId: 'fc19440a-334e-471e-af53-a1c1f53c9226',
redirectUri: 'https://localhost:3000/logoutcomplete/logoutcomplete.html',
postLogoutRedirectUri: 'https://localhost:3000/logoutcomplete/logoutcomplete.html'
}
});
Office.onReady(async () => {
Office.context.ui.addHandlerAsync(Office.EventType.DialogParentMessageReceived,
onMessageFromParent);
pca = new PublicClientApplication({
auth: {
clientId: 'YOUR APP ID HERE',
authority: 'https://login.microsoftonline.com/common',
redirectUri: `${window.location.origin}/login/login.html` // Must be registered as "spa" type.
},
cache: {
cacheLocation: 'localStorage' // Needed to avoid a "login required" error.
}
});
await pca.initialize();
});

msalInstance.logout();
async function onMessageFromParent(arg) {
const messageFromParent = JSON.parse(arg.message);
const currentAccount = pca.getAccountByHomeId(messageFromParent.userName);
// You can select which account application should sign out.
const logoutRequest = {
account: currentAccount,
postLogoutRedirectUri: `${window.location.origin}/logoutcomplete/logoutcomplete.html`,
};
})();
await pca.logoutRedirect(logoutRequest);
const messageObject = { messageType: "dialogClosed" };
const jsonMessage = JSON.stringify(messageObject);
Office.context.ui.messageParent(jsonMessage);
}
Loading