Reputation: 71
I am using the msal library from npm (version 0.1.3) in a react application and can successfully redirect the user to login in and then acquire an access token. The issue I'm having is that after an hour the token will timeout and my API will return a 401.
I notice that when I refresh the SPA in the browser the msalRenewFrame iframe no longer appears in the html source even though I reinitialize the Msal.UserAgentApplication each time, however I'm not sure if that's the issue because the app times out even when I haven't refreshed.
Below is the code that runs each time the app is loaded:
const authCallback = (errorDesc: string, token: string, error: string, tokenType: string) => {
console.log('authCallback (errorDesc, token, error, tokenType)', errorDesc, token, error, tokenType);
if (error) {
console.error(error);
}
let scopes = [
process.env.REACT_APP_AZURE_SCOPE_URL + '/read',
process.env.REACT_APP_AZURE_SCOPE_URL + '/write'
];
msal.acquireTokenSilent(scopes)
.then(scopeApiToken => {
apiToken = scopeApiToken;
sessionStorage.setItem('apiToken', scopeApiToken);
renderApp();
})
.catch(e => {
console.error(e);
});
};
msal = new Msal.UserAgentApplication(
process.env.REACT_APP_AZURE_B2C_WEB_CLIENT_APPID!,
process.env.REACT_APP_AZURE_B2C_SIGNIN_URL!,
authCallback,
{
redirectUri: window.location.origin,
logger: new Msal.Logger((level: Msal.LogLevel, message: string, containsPii: boolean) => {
console.log(message);
})
}
);
let user = msal.getUser();
let isCallback = msal.isCallback(window.location.hash);
if (apiToken) {
renderApp();
} else if (user || isCallback) {
ReactDOM.render(
<div>
<Login
content={<Spinner size={SpinnerSize.medium} label="Signing in" />}
/>
</div>,
root);
} else {
ReactDOM.render(
<div>
<Login
redirectToRoot={true}
content={
<PrimaryButton onClick={() => msal.loginRedirect(['openid'])}>
Sign in with Microsoft
</PrimaryButton>}
/>
</div>,
root);
}
Upvotes: 4
Views: 2269
Reputation: 71
Well, after earning a tumbleweed badge for this post I figured out the answer was that I needed to call msal.acquireTokenSilent each time I wanted to call the external API. (I had been mistakenly thought the msal library would continuously update it silently in the background).
msal.acquireTokenSilent(scopes);
Upvotes: 3