Skip to content

[msal-node] Update silent flow sample UI #1888

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

Merged
merged 15 commits into from
Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from 8 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,4 @@ lib/msal-core/lib-es6
*.tgz
*.zip
samples/**/test/screenshots
samples/**/data/cache.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@
"client_id": "mock_client_id"
}
}
}
}
32 changes: 32 additions & 0 deletions samples/msal-node-samples/msal-node-silent-flow/graph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const fetch = require('node-fetch');

module.exports = {
callMSGraph: function(endpoint, accessToken, callback) {
const headers = new fetch.Headers();
const bearer = `Bearer ${accessToken}`;

headers.append("Authorization", bearer);

const options = {
method: "GET",
headers: headers
};

console.log('request made to Graph API at: ' + new Date().toString());

fetch(endpoint, options)
.then(response => response.json())
.then(response => callback(response, endpoint))
.catch(error => console.log(error));
},

buildGraphProfile: function(graphResponse) {
return {
name: graphResponse.displayName,
title: graphResponse.jobTitle,
mail: graphResponse.mail,
phone: graphResponse.businessPhones[0],
location: graphResponse.officeLocation
}
}
};
100 changes: 90 additions & 10 deletions samples/msal-node-samples/msal-node-silent-flow/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@
* Licensed under the MIT License.
*/
const express = require("express");
const exphbs = require('express-handlebars');
const msal = require('@azure/msal-node');
const { promises: fs } = require("fs");

const graph = require('./graph');

const SERVER_PORT = process.env.PORT || 3000;

/**
* Cache Plugin configuration
*/
const cachePath = "./data/example.cache.json"; // Replace this string with the path to your valid cache file.

const readFromStorage = () => {
return fs.readFile("./data/cache.json", "utf-8");
return fs.readFile(cachePath, "utf-8");
};

const writeToStorage = (getMergedState) => {
return readFromStorage().then(oldFile =>{
const mergedState = getMergedState(oldFile);
return fs.writeFile("./data/cacheAfterWrite.json", mergedState);
return fs.writeFile(cachePath, mergedState);
})
};

Expand All @@ -24,6 +32,14 @@ const cachePlugin = {
writeToStorage
};


const graphConfig = {
graphMeEndpoint: 'https://graph.microsoft.com/v1.0/me'
};

/**
* Public Client Application Configuration
*/
const publicClientConfig = {
auth: {
clientId: "99cab759-2aab-420b-91d8-5e3d8d4f063b",
Expand All @@ -34,35 +50,99 @@ const publicClientConfig = {
cachePlugin
},
};

/** Request Configuration */

const scopes = ["user.read"];

const authCodeUrlParameters = {
scopes: scopes,
redirectUri: ["http://localhost:3000/redirect"],
};

const pca = new msal.PublicClientApplication(publicClientConfig);
const msalCacheManager = pca.getCacheManager();
let accounts;

// Create Express App and Routes
/**
* Express App
*/
const app = express();

// Set handlebars view engine
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');

/**
* App Routes
*/
app.get('/', (req, res) => {
res.render("login", { showSignInButton: true});
});

// Initiates Auth Code Grant
app.get('/login', (req, res) => {
pca.getAuthCodeUrl(authCodeUrlParameters)
.then((response) => {
console.log(response);
res.redirect(response);
})
.catch((error) => console.log(JSON.stringify(error)));
});

// Second leg of Auth Code grant
app.get('/redirect', (req, res) => {
const tokenRequest = {
code: req.query.code,
redirectUri: "http://localhost:3000/redirect",
scopes: scopes,
};

pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
const templateParams = { showLoginButton: false, username: response.account.username, profile: false};
res.render("graph", templateParams);
return msalCacheManager.writeToPersistence();
}).catch((error) => {
console.log(error);
res.status(500).send(error);
});
});

// Initiates Acquire Token Silent flow
app.get('/graphCall', (req, res) => {
// get Accounts
accounts = msalCacheManager.getAllAccounts();
console.log("Accounts: ", accounts);

// Build silent request
const silentRequest = {
account: accounts[1],
redirectUri: "http://localhost:3000/redirect",
account: accounts[1], // Index must match the account that is trying to acquire token silently
scopes: scopes,
};

// get url to sign user in and consent to scopes needed for application
let templateParams = { showLoginButton: false };
// Acquire Token Silently to be used in MS Graph call
pca.acquireTokenSilent(silentRequest)
.then((response) => {
console.log("\nResponse: \n:", response);
res.send(200);
return msalCacheManager.writeToPersistence();
console.log("\nSuccessful silent token acquisition:\nResponse: \n:", response);
const username = response.account.username;
// Call graph after successfully acquiring token
graph.callMSGraph(graphConfig.graphMeEndpoint, response.accessToken, (response, endpoint) => {
// Successful silent request
templateParams = {
...templateParams,
username,
profile: graph.buildGraphProfile(response)
};
res.render("graph", templateParams)
return msalCacheManager.writeToPersistence();
});
})
.catch((error) => {
console.log(error);
res.status(500).send(error);
templateParams.couldNotAcquireToken = true;
res.render("graph", templateParams)
});
});

Expand Down
Loading