Skip to content

Instantly share code, notes, and snippets.

@joanjane
Last active September 7, 2020 10:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joanjane/61cbed87ba19ad01c923078704f66f8f to your computer and use it in GitHub Desktop.
Save joanjane/61cbed87ba19ad01c923078704f66f8f to your computer and use it in GitHub Desktop.
Sample of authentication with msaljs with Azure B2C login automatic
<html>
<head>
<title>Authentication with Msal.js app</title>
</head>
<body>
<!-- bluebird only needed if this page needs to run on Internet Explorer -->
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script src="//rawgit.com/AzureAD/microsoft-authentication-library-for-js/v0.1.3/dist/msal.min.js"></script>
<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<h1>Login with msal.js and Azure B2C</h1>
<div>
<div id="label">Loading...</div>
<button id="auth" onclick="logout();" style="display: none">Log out</button>
</div>
<pre class="response"></pre>
<script>
var applicationConfig = {
clientId: '...',
scopes: ['openid'],
authority: "..."
};
var app = null,
accessToken = null;
function startUp() {
const windowHash = window.location.hash;
app = new Msal.UserAgentApplication(
applicationConfig.clientId,
applicationConfig.authority,
function (errorDesc, token, error, tokenType) {
console.log(arguments);
if (errorDesc || error || !app.getUser()) {
console.log(error + ': ' + errorDesc);
loginRedirect();
return;
}
acquireToken();
},
{
cacheLocation: 'localStorage'
});
app.getUser(); // workaround for msal issue #144
// setTimeout; workaround; for refreshing page after login;
setTimeout(function() {
if (!app.isCallback(windowHash) && window.parent === window && !window.opener) {
// bootstrap flow
console.log('no callback');
acquireToken();
}
}, 1000);
}
function acquireToken() {
app.getUser(); // issue https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/144 workaround
return app.acquireTokenSilent(applicationConfig.scopes)
.then(function(token) {
console.log(token);
accessToken = token;
updateUI();
}, function(error) {
accessToken = null;
console.log(error);
loginRedirect(); // redirect to login when cannot get an access token
});
}
function updateUI() {
var logoutButton = document.getElementById('auth');
logoutButton.style.cssText = 'display: block';
var label = document.getElementById('label');
label.innerText = "Hello " + app.getUser().name + "!";
}
function loginRedirect() {
app.loginRedirect(applicationConfig.scopes);
}
function logout() {
// Removes all sessions, need to call AAD endpoint to do full logout
app.logout();
}
startUp();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment