Last active
May 13, 2024 08:22
-
-
Save LauraKokkarinen/50bb6291065415a27dc0faee83c27d98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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