-
Notifications
You must be signed in to change notification settings - Fork 5k
Initialize MSAL before use to fix auth regression #2685
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
pamelafox
merged 5 commits into
Azure-Samples:main
from
pamelafox:fix/msal-initialize-and-stable-instance
Aug 21, 2025
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
251f4ab
frontend: Initialize MSAL before use, use stable instance, and guard …
pamelafox 5356dfe
frontend: inline catch for checkLoggedIn during auth init; keep initi…
pamelafox f213e75
Use different approach with MsalProvider in index
pamelafox d39706b
Merge branch 'main' into fix/msal-initialize-and-stable-instance
pamelafox eadd7f2
Merge branch 'main' into fix/msal-initialize-and-stable-instance
pamelafox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,45 +1,75 @@ | ||
import { AccountInfo, EventType, PublicClientApplication } from "@azure/msal-browser"; | ||
import { AuthenticationResult, EventType, PublicClientApplication } from "@azure/msal-browser"; | ||
import { checkLoggedIn, msalConfig, useLogin } from "./authConfig"; | ||
import { useEffect, useState } from "react"; | ||
import { useEffect, useMemo, useRef, useState } from "react"; | ||
import { MsalProvider } from "@azure/msal-react"; | ||
import { LoginContext } from "./loginContext"; | ||
import Layout from "./pages/layout/Layout"; | ||
|
||
const LayoutWrapper = () => { | ||
const [loggedIn, setLoggedIn] = useState(false); | ||
if (useLogin) { | ||
var msalInstance = new PublicClientApplication(msalConfig); | ||
// Create a stable MSAL instance (avoid re-init/duplicate listeners; single shared client for MsalProvider). | ||
const msalInstance = useMemo(() => new PublicClientApplication(msalConfig), []); | ||
const [initialized, setInitialized] = useState(false); | ||
// Track mount state so we don't call setState after unmount if async init resolves late | ||
const mounted = useRef<boolean>(true); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The new mounted ref is to avoid setState calls inside the async init() below if the component unmounts during all that. Don't know how common that is. |
||
|
||
// Default to using the first account if no account is active on page load | ||
if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) { | ||
// Account selection logic is app dependent. Adjust as needed for different use cases. | ||
msalInstance.setActiveAccount(msalInstance.getActiveAccount()); | ||
} | ||
useEffect(() => { | ||
// React StrictMode in development invokes effects twice (mount -> cleanup -> mount). | ||
// Reset the flag here so this run is considered mounted. | ||
mounted.current = true; | ||
const init = async () => { | ||
try { | ||
await msalInstance.initialize(); | ||
|
||
// Listen for sign-in event and set active account | ||
msalInstance.addEventCallback(event => { | ||
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) { | ||
const account = event.payload as AccountInfo; | ||
msalInstance.setActiveAccount(account); | ||
} | ||
}); | ||
// Default to using the first account if no account is active on page load | ||
if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) { | ||
// Account selection logic is app dependent. Adjust as needed for different use cases. | ||
msalInstance.setActiveAccount(msalInstance.getAllAccounts()[0]); | ||
pamelafox marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
useEffect(() => { | ||
const fetchLoggedIn = async () => { | ||
setLoggedIn(await checkLoggedIn(msalInstance)); | ||
// Listen for sign-in event and set active account | ||
msalInstance.addEventCallback(event => { | ||
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) { | ||
const result = event.payload as AuthenticationResult; | ||
if (result.account) { | ||
msalInstance.setActiveAccount(result.account); | ||
} | ||
} | ||
}); | ||
|
||
if (mounted.current) { | ||
const isLoggedIn = await checkLoggedIn(msalInstance).catch(e => { | ||
// Swallow check error but still allow app to render | ||
console.error("checkLoggedIn failed", e); | ||
return false; | ||
}); | ||
setLoggedIn(isLoggedIn); | ||
} | ||
} catch (e) { | ||
console.error("MSAL initialize failed", e); | ||
} finally { | ||
if (mounted.current) { | ||
setInitialized(true); | ||
} | ||
} | ||
}; | ||
init(); | ||
return () => { | ||
// On unmount: flag as unmounted so any pending async in init() doesn't call setState | ||
// This avoids React warnings about setting state on an unmounted component. | ||
mounted.current = false; | ||
}; | ||
}, [msalInstance]); | ||
|
||
fetchLoggedIn(); | ||
}, []); | ||
if (!initialized) { | ||
// Lightweight placeholder while MSAL initializes | ||
return <p>Loading authentication…</p>; | ||
} | ||
|
||
return ( | ||
<MsalProvider instance={msalInstance}> | ||
<LoginContext.Provider | ||
value={{ | ||
loggedIn, | ||
setLoggedIn | ||
}} | ||
> | ||
<LoginContext.Provider value={{ loggedIn, setLoggedIn }}> | ||
<Layout /> | ||
</LoginContext.Provider> | ||
</MsalProvider> | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cline's suggested fix did not use useMemo, but Copilot+GPT5 thought it was a good idea, to avoid re-construction across renders.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The docs show this general type of pattern for accomplishing that (without useMemo()), but useMemo() should achieve the goal of ensuring it's only created once. I don't know enough about the app to understand the overall flow and how often the component is rerendered. But, assuming it is, useMemo should help there.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's an SPA - my understanding is that this wrapper holds all the content displayed and shouldn't be re-rendered unless the page is refreshed