Skip to content

Instantly share code, notes, and snippets.

@LauraKokkarinen
Last active May 13, 2024 08:22
Show Gist options
  • Save LauraKokkarinen/50bb6291065415a27dc0faee83c27d98 to your computer and use it in GitHub Desktop.
Save LauraKokkarinen/50bb6291065415a27dc0faee83c27d98 to your computer and use it in GitHub Desktop.
import { InteractionRequiredAuthError, IPublicClientApplication } from "@azure/msal-browser";
let msalInstance: IPublicClientApplication;
export const setMsalInstance = async (instance: IPublicClientApplication) => {
msalInstance = instance;
await msalInstance.initialize();
}
const getAccessToken = async (scopes: string[]): Promise<string | null> => {
let authResult = null;
const account = msalInstance.getActiveAccount() ?? msalInstance.getAllAccounts()[0];
try {
authResult = await msalInstance.acquireTokenSilent({ scopes: scopes, account: account })
}
catch (error) {
if (error instanceof InteractionRequiredAuthError) {
authResult = await msalInstance.acquireTokenPopup({ scopes: scopes })
}
}
return authResult ? authResult.accessToken : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment