microsoft-authentication-library-for-js icon indicating copy to clipboard operation
microsoft-authentication-library-for-js copied to clipboard

UnauthenticatedTemplate / AuthenticatedTemplate behavior has changed, now authenticated before setActiveAccount is called

Open 4imble opened this issue 6 months ago • 0 comments

Core Library

MSAL.js (@azure/msal-browser)

Core Library Version

3.20.0

Wrapper Library

MSAL React (@azure/msal-react)

Wrapper Library Version

2.0.22

Public or Confidential Client?

Confidential

Description

My application has started failing with new devs that come onto the project. It seems something has changed between msal-react 20.0.14 and 20.0.22. I upgraded myself and the problem has presented itself me too. The error is as follows: BrowserAuthError: no_account_error: No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.

I have narrowed this down and have found why it's happening, I'll elaborate in the steps below.

I can fix this by moving setActiveAccount to somewhere higher up and checking if accounts has items then setActiveAccount but wondered if this was an unintended breaking change?

Error Message

chunk-UK5AGQUA.js?v=71bff973:7877 Uncaught (in promise) BrowserAuthError: no_account_error: No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request. at createBrowserAuthError (chunk-UK5AGQUA.js?v=71bff973:7877:10) at _StandardController.acquireTokenSilent (chunk-UK5AGQUA.js?v=71bff973:14311:13) at _PublicClientApplication.acquireTokenSilent (chunk-UK5AGQUA.js?v=71bff973:15195:28) at Server.getTokenRequest (App.tsx:64:33) at Server.jsonRpc (server.ts:38:45) at Server.rpcInstance (server.ts:29:29) at getCommonData (master-page.tsx:49:39) at master-page.tsx:54:13 at commitHookEffectListMount (chunk-3IHV7RO6.js?v=71bff973:16915:34) at commitPassiveMountOnFiber (chunk-3IHV7RO6.js?v=71bff973:18156:19)

MSAL Logs

Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtools authConfig.ts:38 [Thu, 01 Aug 2024 09:26:18 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - Emitting event: msal:initializeStart authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - Emitting event: msal:initializeEnd authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - Emitting event: msal:handleRedirectStart authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [01910d42-fa92-7ec7-ad17-84a9b0f50995] : [email protected] : Info - handleRedirectPromise called but there is no interaction in progress, returning null. authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - Emitting event: msal:handleRedirectEnd authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - MsalProvider - msal:handleRedirectStart results in setting inProgress from startup to handleRedirect authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - MsalProvider - msal:handleRedirectEnd results in setting inProgress from handleRedirect to none 2authConfig.ts:38 [Thu, 01 Aug 2024 09:26:19 GMT] : [] : @azure/[email protected] : Info - CacheManager:getIdToken - No token found

Network Trace (Preferrably Fiddler)

  • [ ] Sent
  • [X] Pending

MSAL Configuration

export const msalConfig = {
    auth: {
        clientId: import.meta.env.VITE_AUTH_CLIENTID,
        authority: `${import.meta.env.VITE_AUTH_AUTHORITY}/adfs/`,
        knownAuthorities: [import.meta.env.VITE_AUTH_AUTHORITY],
        redirectUri: "/"
    },
    cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false,
    },
    system: {	
        loggerOptions: {	
            logLevel: LogLevel.Verbose,
            loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => {	
                if (containsPii || !enableLogging) {		
                    return;		
                }		
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                    default:
                        return;
                }	
            }	
        }	
    }
};

Relevant Code Snippets

<UnauthenticatedTemplate>
                <Routes>
                    <Route path="/*" element={<Login></Login>} />
                </Routes>
            </UnauthenticatedTemplate>

            <AuthenticatedTemplate>
                    <Routes>
                        <Route path="/" element={<HomePage></HomePage>} />
                        <Route path="*" element={<NotFound></NotFound>} />
                    </Routes>
            </AuthenticatedTemplate>
export default function Login() {
    const { instance, accounts } = useMsal();

    useEffect(() => {
        let init = async () => {
            try {
                if (!accounts.length) {
                    await instance.initialize();
                    await instance.loginRedirect(loginRequest);
                }

                if (!instance.getActiveAccount() && instance.getAllAccounts().length) {
                    instance.setActiveAccount(instance.getAllAccounts()[0]);
                }
            }
            catch (ex) {
                console.error("Unable to authenticate", ex);
            }
        }

        init();
    }, [accounts]);

    return (<Loader message='Authenticating user ...'></Loader>)
}


### Reproduction Steps

1) redirect to login, come back and WILL be authenticated. 
2) Hit authenticated routes and fails because `setActiveAccount` is not called.

### Expected Behavior

1) redirect to login, come back and NOT be authenticated. 
2) Hit login again but now have an account so skips redirect and calls `setActiveAccount`
3) User now authenticated and thus router serves up new routes due to <AuthenticatedTemplate />

### Identity Provider

ADFS

### Browsers Affected (Select all that apply)

Chrome, Edge

### Regression

azure/msal-react@npm:2:0.14

### Source

External (Customer)

4imble avatar Aug 01 '24 09:08 4imble