Skip to content

Instantly share code, notes, and snippets.

@rayterrill
Last active August 12, 2019 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayterrill/e88b9e54694bdf96a97e3f1a17428cfd to your computer and use it in GitHub Desktop.
Save rayterrill/e88b9e54694bdf96a97e3f1a17428cfd to your computer and use it in GitHub Desktop.
Had a hell of a time trying to grok MSAL with simple, fully functional examples - the documentation still is pretty weak. Here are two examples showing both the redirect and popup flows. Hope it helps someone out
<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="leftContainer">
<p id="WelcomeMessage">Welcome to the Microsoft Authentication Library For Javascript Quickstart</p>
<button id="SignIn" onclick="signIn()">Sign In</button>
</div>
<div class="rightContainer">
<pre id="json"></pre>
</div>
</div>
</body>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.1.2/js/msal.min.js"></script>
<script type="text/javascript">
//
//REPLACE THE clientID AND authority FIELDS WITH YOUR VALUES FROM AZUREAD, AS WELL AS THE scopes FIELD IF YOU NEED AN ACCESS TOKEN
//
var msalConfig = {
auth: {
clientId: 'CLIENT_ID_FROM_AZUREAD',
authority: 'https://login.microsoftonline.com/YOURDOMAIN.onmicrosoft.com'
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var msalInstance = new Msal.UserAgentApplication(msalConfig);
var loginRequest = {
scopes: ["user.read"] // optional Array<string>
};
function signIn() {
msalInstance.loginPopup(loginRequest).then(function (loginResponse) {
//Successful login
showWelcomeMessage();
}).catch(function (error) {
//Please check the console for errors
console.log(error);
});
}
function showWelcomeMessage() {
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = "Welcome " + msalInstance.getAccount().userName + " to Microsoft Graph API";
var loginbutton = document.getElementById('SignIn');
loginbutton.innerHTML = 'Sign Out';
loginbutton.setAttribute('onclick', 'signOut();');
}
if (msalInstance.getAccount()) {
showWelcomeMessage();
//if you need to get a token for an internal API with your app - use the CLIENT_ID for your app - i.e. scopes: [CLIENT_ID_FROM_AZUREAD]
//if you need to get a token for graphapi - use the scopes you need to retrieve - i.e. scopes: ["user.read", "mail.send"]
let accessTokenRequest = {
scopes: [CLIENT_ID_FROM_AZUREAD]
}
msalInstance.acquireTokenSilent(accessTokenRequest)
.then( (accessTokenResponse) => {
//access token was successfully received via the silent request
//token is available at accessTokenResponse.accessToken
}).catch( (error) => {
//error getting a token
if (err.name === "InteractionRequiredAuthError") {
return msalInstance.acquireTokenRedirect(accessTokenRequest)
.then(function (accessTokenResponse) {
//we needed to do a redirect to get a token
//token is available at accessTokenResponse.accessToken
})
.catch(err => {
console.log('failed to get a token');
});
}
});
} else {
signIn();
}
</script>
</html>
<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="leftContainer">
<p id="WelcomeMessage">Welcome to the Microsoft Authentication Library For Javascript Quickstart</p>
<button id="SignIn" onclick="signIn()">Sign In</button>
</div>
<div class="rightContainer">
<pre id="json"></pre>
</div>
</div>
</body>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.1.2/js/msal.min.js"></script>
<script type="text/javascript">
//
//REPLACE THE clientID AND authority FIELDS WITH YOUR VALUES FROM AZUREAD, AS WELL AS THE scopes FIELD IF YOU NEED AN ACCESS TOKEN
//
var msalConfig = {
auth: {
clientId: 'CLIENT_ID_FROM_AZUREAD',
authority: 'https://login.microsoftonline.com/YOURDOMAIN.onmicrosoft.com'
}
};
var msalInstance = new Msal.UserAgentApplication(msalConfig);
msalInstance.handleRedirectCallback(function (error, response) {
if (error) {
console.log(error);
} else {
console.log("token type is:" + response.tokenType);
}
});
var loginRequest = {
scopes: ["user.read"] // optional
};
function signIn() {
msalInstance.loginRedirect(loginRequest);
}
function showWelcomeMessage() {
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = "Welcome " + msalInstance.getAccount().userName + " to Microsoft Graph API";
var loginbutton = document.getElementById('SignIn');
loginbutton.innerHTML = 'Sign Out';
loginbutton.setAttribute('onclick', 'signOut();');
}
if (msalInstance.getAccount() && !msalInstance.isCallback(window.location.hash)) {// avoid duplicate code execution on page load in case of iframe and popup window.
showWelcomeMessage();
//if you need to get a token for an internal API with your app - use the CLIENT_ID for your app - i.e. scopes: [CLIENT_ID_FROM_AZUREAD]
//if you need to get a token for graphapi - use the scopes you need to retrieve - i.e. scopes: ["user.read", "mail.send"]
let accessTokenRequest = {
scopes: [CLIENT_ID_FROM_AZUREAD]
}
msalInstance.acquireTokenSilent(accessTokenRequest)
.then( (accessTokenResponse) => {
//access token was successfully received via the silent request
//token is available at accessTokenResponse.accessToken
}).catch( (error) => {
//error getting a token
if (err.name === "InteractionRequiredAuthError") {
return msalInstance.acquireTokenRedirect(accessTokenRequest)
.then(function (accessTokenResponse) {
//we needed to do a redirect to get a token
//token is available at accessTokenResponse.accessToken
})
.catch(err => {
console.log('failed to get a token');
});
}
});
} else {
signIn();
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment