Last active
June 25, 2025 16:40
-
-
Save loucadufault/2e5cb99d9f8f93d35856b09c804978dd to your computer and use it in GitHub Desktop.
React hook abstracting over usage of MSAL.js APIs to acquire an access token (silently first, then with a redirect)
This file contains hidden or 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 { BrowserAuthError, BrowserAuthErrorMessage, InteractionRequiredAuthError, type RedirectRequest, type SilentRequest } from '@azure/msal-browser' | |
import { useMsal } from '@azure/msal-react' | |
import { useCallback } from 'react' | |
export const useMsalAuthentication = ({ | |
silentRequest, | |
redirectRequest, | |
}: { | |
silentRequest: SilentRequest | |
redirectRequest: RedirectRequest | |
}): { | |
acquireAccessToken: () => Promise<string> | |
} => { | |
const { instance, accounts } = useMsal() | |
const acquireAccessToken = useCallback( | |
() => | |
instance | |
.acquireTokenSilent({ | |
...silentRequest, | |
// TODO: maybe we can delegate to MSAL library to infer this | |
account: accounts[0], | |
}) | |
.then(({ accessToken }) => accessToken) | |
.catch((e) => { | |
if ( | |
e instanceof InteractionRequiredAuthError || | |
(e instanceof BrowserAuthError && e.errorCode === BrowserAuthErrorMessage.noAccountError.code) | |
) { | |
// NOTE: in reality the return type is never, since this redirects the page | |
return instance.acquireTokenRedirect(redirectRequest) as never | |
} | |
throw e | |
}), | |
[accounts, instance], | |
) | |
return { | |
acquireAccessToken, | |
} | |
} |
This file contains hidden or 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
const WebApiInterface = () => { | |
const { | |
acquireAccessToken, | |
} = useMsalAuthentication({ | |
silentRequest: {}, | |
redirectRequest: {}, | |
}) | |
return ( | |
<Button onClick={acquireAccessToken().then((accessToken) => makeWebApiCall(accessToken)).catch((e) => console.error(e))}> | |
Call Web API | |
</Button> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's recommended not to store the access token as React state, since it will eventually become stale. Instead, every attempt to use the access token should use the function to acquire it.