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 4 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
6 changes: 2 additions & 4 deletions Samples/auth/Office-Add-in-Microsoft-Graph-React/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/logkout.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.
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
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
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
},
cache: {
cacheLocation: 'localStorage', // needed to avoid "login required" error
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
storeAuthStateInCookie: true // recommended to avoid certain IE/Edge issues
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
}
});
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
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
const response = await pca.handleRedirectPromise();
if (response) {
Office.context.ui.messageParent(JSON.stringify({ status: 'success', token: response.accessToken, userName: response.account.username}));
} else {
// Problem occurred, so invoke login
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
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
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
},
cache: {
cacheLocation: 'localStorage', // needed to avoid "login required" error
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
storeAuthStateInCookie: true // recommended to avoid certain IE/Edge issues
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
}
});
await pca.initialize();
});

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

// you can select which account application should sign out
davidchesnut marked this conversation as resolved.
Show resolved Hide resolved
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