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 7 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
10 changes: 4 additions & 6 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 @@ -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
}
}
});

66 changes: 32 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,38 @@

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: 'https://localhost:3000/login/login.html' // Must be registered as "spa" type.
Copy link
Collaborator

Choose a reason for hiding this comment

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

${window.location.origin}/login/login.html will still work after publish to server

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed.

},
cache: {
cacheLocation: 'localStorage', // Needed to avoid a "login required" error.
storeAuthStateInCookie: true // Recommended to avoid certain IE/Edge issues.
Copy link
Collaborator

Choose a reason for hiding this comment

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

don't think this is still necessary

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed.

}
});
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.
pca.loginRedirect({
Copy link
Collaborator

Choose a reason for hiding this comment

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

this is a Promise, may want to await it so that the catch block could work properly if error.

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed.

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 }));
});
};
})();
41 changes: 29 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,35 @@

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: 'https://localhost:3000/login/login.html' // Must be registered as "spa" type.
},
cache: {
cacheLocation: 'localStorage', // Needed to avoid a "login required" error.
storeAuthStateInCookie: true // Recommended to avoid certain IE/Edge issues.
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think you can remove this setting

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed.

}
});
await pca.initialize();
});

msalInstance.logout();
async function onMessageFromParent(arg) {
const messageFromParent = JSON.parse(arg.message);

// You can select which account application should sign out.
const logoutRequest = {
account: messageFromParent.userName,
Copy link
Collaborator

Choose a reason for hiding this comment

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

account property is AccountInfo, not a string. I don't think this will be used, it may even cause issues.

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed.

postLogoutRedirectUri: "https://localhost:3000/logoutcomplete/logoutcomplete.html",
};
})();
await pca.logoutRedirect(logoutRequest);
const messageObject = { messageType: "dialogClosed" };
const jsonMessage = JSON.stringify(messageObject);
Office.context.ui.messageParent(jsonMessage);
}
Loading