Skip to content

Instantly share code, notes, and snippets.

Last active November 7, 2023 20:20
Show Gist options
  • Save adriancuadrado/dec7bca85c673cc2d75e0ad5e733688f to your computer and use it in GitHub Desktop.
Save adriancuadrado/dec7bca85c673cc2d75e0ad5e733688f to your computer and use it in GitHub Desktop.
MSAL.js cheatsheet
// Initialization
const myMSALObj = new msal.PublicClientApplication({
auth: {
clientId: "c993fdd7-f80e-4586-bd81-8753a1f3e5ac", // This is the ONLY mandatory field; everything else is optional.
authority: "", // Choose sign-up/sign-in user-flow as your default.
knownAuthorities: [''], // You must identify your tenant's domain as a known authority.
redirectUri: "http://localhost:6420" // You must register this URI on Azure Portal/App Registration. Defaults to "window.location.href".
cache: {
cacheLocation: "sessionStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
storeAuthStateInCookie: false // If you wish to store cache items in cookies as well as browser cache, set this to "true".
// Save the token after returning from redirection. This must be executed on every page load.
.then(response => {
if (!response) {
console.log('You are not coming from a redirect');
} else {
// I don't really know which properties does the response object contain other than `idTokenClaims` and `account`.
.catch(error => {
// I am not sure if you can use this catch to know if the user cancelled, or if it is just for server errors.
// Login
scopes: [
// Logout
postLogoutRedirectUri: 'http://localhost:6420',
// Get saved accounts
// Note: The objects of this funciton have the same format as the one returned from `handleRedirectPromise()` in `response.account`.
// Check stored access token and redirect if we don't have one
const request = {
account: myMSALObj.getAllAccounts()[0],
scopes: [
forceRefresh: false
.then(response => {
if (response.accessToken) {
} else {
return myMSALObj.acquireTokenRedirect(request);
// Request with the access token
fetch('http://localhost:5000/hello', {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`
// User's name
// Make sure to have the `Display Name` claim configured.
// You might have to manually edit the user from Azure B2C or use the `Profile editing` user flow.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment