Skip to content

Commit 906284c

Browse files
committed
Fix MSAL login for stale sessions
1 parent cd23500 commit 906284c

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

src/ui/components/AuthContext/index.tsx

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -189,23 +189,44 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
189189
if (!checkRoute) {
190190
throw new Error("could not get user roles!");
191191
}
192-
const accountsLocal = instance.getAllAccounts();
193-
if (accountsLocal.length > 0) {
194-
instance.setActiveAccount(accountsLocal[0]);
195-
const api = useApi("core");
196-
const result = await api.get(checkRoute);
197-
await setCachedResponse("core", checkRoute, result.data);
198-
setIsLoggedIn(true);
192+
193+
const accounts = instance.getAllAccounts();
194+
const request = {
195+
scopes: ["openid", "profile", "email"],
196+
state: returnTo,
197+
};
198+
199+
if (accounts.length > 0) {
200+
instance.setActiveAccount(accounts[0]);
201+
try {
202+
await instance.acquireTokenSilent({
203+
...request,
204+
account: accounts[0],
205+
});
206+
const api = useApi("core");
207+
const result = await api.get(checkRoute);
208+
await setCachedResponse("core", checkRoute, result.data);
209+
setIsLoggedIn(true);
210+
} catch (error) {
211+
if (error instanceof InteractionRequiredAuthError) {
212+
await instance.loginRedirect({
213+
...request,
214+
redirectUri: `${window.location.origin}/auth/callback`,
215+
});
216+
} else {
217+
throw error;
218+
}
219+
}
199220
} else {
200221
await instance.loginRedirect({
201-
scopes: ["openid", "profile", "email"],
202-
state: returnTo,
222+
...request,
203223
redirectUri: `${window.location.origin}/auth/callback`,
204224
});
205225
}
206226
},
207-
[instance],
227+
[instance, checkRoute, setIsLoggedIn, setCachedResponse],
208228
);
229+
209230
const setLoginStatus = useCallback((val: boolean) => {
210231
setIsLoggedIn(val);
211232
}, []);

0 commit comments

Comments
 (0)