Skip to content

Popup coop sample #7375

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

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
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
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

124 changes: 124 additions & 0 deletions samples/msal-browser-samples/popup-coop/app/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Browser check variables
// If you support IE, our recommendation is that you sign-in using Redirect APIs
// If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;

let signInType;
let accountId = "";

// Create the main myMSALObj instance
// configuration parameters are located at authConfig.js
const myMSALObj = new msal.PublicClientApplication(msalConfig);

myMSALObj.initialize().then(() => {
// Redirect: once login is successful and redirects with tokens, call Graph API
myMSALObj.handleRedirectPromise().then(handleResponse).catch(err => {
console.error(err);
});
})

function handleResponse(resp) {
if (resp !== null) {
accountId = resp.account.homeAccountId;
myMSALObj.setActiveAccount(resp.account);
showWelcomeMessage(resp.account);
} else {
// need to call getAccount here?
const currentAccounts = myMSALObj.getAllAccounts();
if (!currentAccounts || currentAccounts.length < 1) {
return;
} else if (currentAccounts.length > 1) {
// Add choose account code here
} else if (currentAccounts.length === 1) {
const activeAccount = currentAccounts[0];
myMSALObj.setActiveAccount(activeAccount);
accountId = activeAccount.homeAccountId;
showWelcomeMessage(activeAccount);
}
}
}

async function signIn(method) {
signInType = isIE ? "redirect" : method;
if (signInType === "popup") {
return myMSALObj.loginPopup({
...loginRequest,
redirectUri: "http://localhost:30662"
}).then(handleResponse).catch(function (error) {
console.log(error);
});
} else if (signInType === "redirect") {
return myMSALObj.loginRedirect(loginRequest)
}
}

function signOut(interactionType) {
const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId)
};

if (interactionType === "popup") {
myMSALObj.logoutPopup(logoutRequest).then(() => {
window.location.reload();
});
} else {
myMSALObj.logoutRedirect(logoutRequest);
}
}

async function getTokenPopup(request, account) {
request.redirectUri = "http://localhost:30662"
return await myMSALObj
.acquireTokenSilent(request)
.catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
console.log("acquiring token using popup");
return myMSALObj.acquireTokenPopup(request).catch((error) => {
console.error(error);
});
} else {
console.error(error);
}
});
}

// This function can be removed if you do not need to support IE
async function getTokenRedirect(request, account) {
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
console.log("acquiring token using redirect");
myMSALObj.acquireTokenRedirect(request);
} else {
console.error(error);
}
});
}

function openPopupLmso(){
// const popupWindow = window.open("http://localhost:30662", "popup", "width=600,height=600");
const popupWindow = window.open("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", "popup", "width=600,height=600");
monitorLmsoPopup(popupWindow);
}

function monitorLmsoPopup(popupWindow){
console.log("PopupHandler.monitorPopupLmso - monitoring popup");
const intervalId = setInterval(() => {
// Window is closed
if (popupWindow.closed) {
console.log(
"PopupHandler.monitorPopupLmso - window closed"
);
clearInterval(intervalId);
}
}, 100000);
popupWindow.location = "http://localhost:30662";
popupWindow.close();
};
69 changes: 69 additions & 0 deletions samples/msal-browser-samples/popup-coop/app/authConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "8015f5e0-0370-427c-9b0d-d834189ffdd0",
authority:
"https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
logLevel: msal.LogLevel.Trace,
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
default:
console.log(message);
return;
}
},
},
pollIntervalMilliseconds: 0
},
telemetry: {
application: {
appName: "MSAL Browser V2 Default Sample",
appVersion: "1.0.0",
},
},
};

// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["User.Read"],
};

// Add here the endpoints for MS Graph API services you would like to use.
const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
graphMailEndpoint: "https://graph.microsoft.com/v1.0/me/messages",
};

// Add here scopes for access token to be used at MS Graph API endpoints.
const tokenRequest = {
scopes: ["Mail.Read"],
forceRefresh: false, // Set this to "true" to skip a cached token and go to the server to get a new token
};

const silentRequest = {
scopes: ["openid", "profile", "User.Read", "Mail.Read"],
};

const logoutRequest = {};
64 changes: 64 additions & 0 deletions samples/msal-browser-samples/popup-coop/app/graph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Helper function to call MS Graph API endpoint
// using authorization bearer token scheme
function callMSGraph(endpoint, accessToken, callback) {
const headers = new 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));
}

async function seeProfile() {
const currentAcc = myMSALObj.getAccountByHomeId(accountId);
if (currentAcc) {
const response = await getTokenPopup(loginRequest, currentAcc).catch(error => {
console.log(error);
});
callMSGraph(graphConfig.graphMeEndpoint, response.accessToken, updateUI);
profileButton.style.display = 'none';
}
}

async function readMail() {
const currentAcc = myMSALObj.getAccountByHomeId(accountId);
if (currentAcc) {
const response = await getTokenPopup(tokenRequest, currentAcc).catch(error => {
console.log(error);
});
callMSGraph(graphConfig.graphMailEndpoint, response.accessToken, updateUI);
mailButton.style.display = 'none';
}
}

async function seeProfileRedirect() {
const currentAcc = myMSALObj.getAccountByHomeId(accountId);
if (currentAcc) {
const response = await getTokenRedirect(loginRequest, currentAcc).catch(error => {
console.log(error);
});
callMSGraph(graphConfig.graphMeEndpoint, response.accessToken, updateUI);
profileButton.style.display = 'none';
}
}

async function readMailRedirect() {
const currentAcc = myMSALObj.getAccountByHomeId(accountId);
if (currentAcc) {
const response = await getTokenRedirect(tokenRequest, currentAcc).catch(error => {
console.log(error);
});
callMSGraph(graphConfig.graphMailEndpoint, response.accessToken, updateUI);
mailButton.style.display = 'none';
}
}
82 changes: 82 additions & 0 deletions samples/msal-browser-samples/popup-coop/app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Quickstart | MSAL.JS Vanilla JavaScript SPA</title>

<script src="../../lib/msal-browser.js" type="text/javascript"></script>

<!-- adding Bootstrap 4 for UI components -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="SHORTCUT ICON" href="https://c.s-microsoft.com/favicon.ico?v2" type="image/x-icon">
</head>

<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/">MS Identity Platform</a>
<div class="btn-group ml-auto dropleft">
<button type="button" id="SignIn" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Sign In
</button>
<div class="dropdown-menu">
<button class="dropdown-item" id="popup" onclick="signIn(this.id)">Sign in using Popup</button>
<button class="dropdown-item" id="redirect" onclick="signIn(this.id)">Sign in using Redirect</button>
<button class="dropdown-item" id="popupLmso" onclick="openPopupLmso(this.id)">open lmso popup</button>
</div>
</div>
</nav>
<br>
<h5 class="card-header text-center">Vanilla JavaScript SPA calling MS Graph API with MSAL.JS</h5>
<br>
<div class="row" style="margin:auto">
<div id="card-div" class="col-md-3" style="display:none">
<div class="card text-center">
<div class="card-body">
<h5 class="card-title" id="WelcomeMessage">Please sign-in to see your profile and read your mails</h5>
<div id="profile-div"></div>
<br>
<br>
<button class="btn btn-primary" id="seeProfile" onclick="seeProfile()">See Profile</button>
<br>
<br>
<button class="btn btn-primary" id="readMail" onclick="readMail()">Read Mails</button>
</div>
</div>
</div>
<br>
<br>
<div class="col-md-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-md-5">
<div class="tab-content" id="nav-tabContent">
</div>
</div>
</div>
<br>
<br>

<!-- importing bootstrap.js and supporting js libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>

<!-- importing app scripts | load order is important -->
<script type="text/javascript" src="./authConfig.js"></script>
<script type="text/javascript" src="./ui.js"></script>
<script type="text/javascript" src="./auth.js"></script>
<script type="text/javascript" src="./graph.js"></script>
</body>

</html>
6 changes: 6 additions & 0 deletions samples/msal-browser-samples/popup-coop/app/redirect.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!--
Blank page for redirect purposes. When using popup and silent APIs,
we recommend setting the redirectUri to a blank page or a page that does not implement MSAL.
For more information, please follow this link:
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/login-user.md#redirecturi-considerations
-->
Loading