Skip to content
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

Session not persisting on page reload #6608

Closed
baseloncohost opened this issue Oct 25, 2023 · 23 comments · Fixed by #6622
Closed

Session not persisting on page reload #6608

baseloncohost opened this issue Oct 25, 2023 · 23 comments · Fixed by #6622
Assignees
Labels
b2c Related to Azure B2C library-specific issues bug-unconfirmed A reported bug that needs to be investigated and confirmed msal-browser Related to msal-browser package msal-react Related to @azure/msal-react public-client Issues regarding PublicClientApplications question Customer is asking for a clarification, use case or information.

Comments

@baseloncohost
Copy link

Core Library

MSAL.js (@azure/msal-browser)

Core Library Version

3.3.0

Wrapper Library

MSAL React (@azure/msal-react)

Wrapper Library Version

2.0.5

Public or Confidential Client?

Public

Description

After login, no matter what the config is, whenever you hit reload or open new tab/window the session will not persist and will ask the user to login again.

Downgrading to msal-browser 3.2.0 and msal-react 2.0.4 seems to solve the issue.

Error Message

N/A

Msal Logs

N/A

MSAL Configuration

auth: {
        clientId: AZURE_CLIENT_ID ?? '',
        authority: b2cPolicies.authorityDomain,
        knownAuthorities: [b2cPolicies.authorityDomain ?? ''],
        redirectUri: '/',
        postLogoutRedirectUri: '/auth/login',
        navigateToLoginRequestUrl: false,
    },
    cache: {
        cacheLocation: BrowserCacheLocation.LocalStorage,
        storeAuthStateInCookie: false,
    },

Relevant Code Snippets

N/A

Reproduction Steps

  1. Login
  2. Refresh page OR open new tab
  3. User needs to login again

Expected Behavior

Session should persist through refresh and or opening new tab/window

Identity Provider

Azure B2C Custom Policy

Browsers Affected (Select all that apply)

Chrome, Firefox, Edge, Safari

Regression

@azure/msal-browser@3.2.0

Source

Internal (Microsoft)

@baseloncohost baseloncohost added bug-unconfirmed A reported bug that needs to be investigated and confirmed question Customer is asking for a clarification, use case or information. labels Oct 25, 2023
@microsoft-github-policy-service microsoft-github-policy-service bot added the Needs: Attention 👋 Awaiting response from the MSAL.js team label Oct 25, 2023
@github-actions github-actions bot added b2c Related to Azure B2C library-specific issues msal-browser Related to msal-browser package msal-react Related to @azure/msal-react public-client Issues regarding PublicClientApplications labels Oct 25, 2023
@AndreaEsposit
Copy link

We are having the same problem in our application

@ggegelya
Copy link

I'm using MSAL for Angular and having similar problem. Each time page refresh OR open in a new tab, there's a redirection to authorize/ endpoint and back, which makes browser url 'blink' for the user and also slows down a bit the load of the page as it re-authenticates the user. Could this be related?

@konstantin-msft
Copy link
Collaborator

Thanks for bringing this up and apologies for the incontinence. I am investigating it right now.

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 25, 2023
@ggegelya
Copy link

I tried using claimsBasedCachingEnabled, but seems it's not helping at all. It still re-take auth information from scratch ignoring the one stored in localStorage :(

@alexpvieira
Copy link

Can confirm the issue, downgrading to msal-browser 3.2.0 seems to solve the issue.

@konstantin-msft
Copy link
Collaborator

Are you able to repro this issue with one of the angular/react samples? I can't repro it yet - local storage entries are being honored as expected.

@konstantin-msft konstantin-msft self-assigned this Oct 25, 2023
@konstantin-msft
Copy link
Collaborator

@baseloncohost Can you please check if cleaning up the local cache helps to fix the issue? I am not able to repro it with MSAL react/angular samples. Trying to narrow down the potential causes.

@ggegelya
Copy link

@konstantin-msft My scenario seems to be reproducible using sample application. I still not sure that my scenario is related to the authors @baseloncohost post. If not, please let me know so I can create separate issue.

I've created blank angular app, and made necessary changes to replicate sample for Angular 16 (copy/paste code)
Use-case I tried:

  • log-in
  • go to Profile and ensure it shows information about me
  • I refresh the page:
    • at this moment I was able to see app.component.html for tick of a second,
    • then I saw redirect to login.microsoft.com,
    • then redirect back to app.component.html (#code in url was visible for tick of a second)
    • then back to profile

In the past when I used v2 it works using token from the cache, but now it overwrites it each refresh of the page.
Is it normal behavior?

@konstantin-msft
Copy link
Collaborator

@ggegelya Thanks for responding. Unfortunately, I still can't repro the issue. Would you be able to repeat the same steps please with verbose logging enabled (see docs for details) and share the full output?

@ggegelya
Copy link

@konstantin-msft sure thing, there you go
tried clean reproduction of the use-case with Preserve Log enabled (so it will be saved between refresh of the pages.
Did logout before to have clean result

localhost-1698264852900.log

@thushanperera95
Copy link

We're having the same problem.
Using @azure/msal-browser v3.3.0 with cacheLocation: "localStorage" and claimsBasedCachingEnabled: true.

I've noticed that PublicClientApplication.getAllAccounts() always returns an empty array. Doesn't look like it's picking up the cached accounts.

@baseloncohost
Copy link
Author

@konstantin-msft

Running the sample typescript app with the configurations gives same behavior, refresh page will ask for login again. I did clear cache.
I also tested on Safari, Firefox and Chrome with same behaviour.

Installed packages:

├── @azure/msal-browser@3.3.0
├── @azure/msal-react@2.0.5
├── @babel/plugin-proposal-private-property-in-object@7.21.11
├── @emotion/react@11.11.1
├── @emotion/styled@11.11.0
├── @mui/icons-material@5.14.15
├── @mui/material@5.14.15
├── @types/jest@29.5.6
├── @types/node@16.18.59
├── @types/react-dom@18.2.14
├── @types/react-router-dom@5.3.3
├── @types/react@18.2.33
├── jest@29.7.0
├── react-dom@18.2.0
├── react-router-dom@6.17.0
├── react-scripts@5.0.1
├── react@18.2.0
├── ts-jest@29.1.1
└── typescript@4.9.5

However, locking the @azure/msal-browser to version 3.2.0 seems to solve the problem and the expected behaviour of session persisting is observed.

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 Awaiting response from the MSAL.js team and removed Needs: Author Feedback Awaiting response from issue author labels Oct 26, 2023
@jcag-teagasc
Copy link

We are having this issue using @msal-browser": "3.3.0" in React. On page refresh user is forced to sign in again. Reverted to version 3.2.0 and refresh works fine again

@ggegelya
Copy link

@konstantin-msft for info, I was able to reproduce it on the following versions:

@azure/msal-angular: "^3.0.4
@azure/msal-browser: "^3.1.0

@miguellira
Copy link

miguellira commented Oct 27, 2023

@konstantin-msft same experience with latest bits. Downgraded to msal-browser 3.2.0 fixes this. Any chance this has something to do with how the Application has to be instantiated?

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/v2-migration.md#application-instantiation

@ArvidAnderson
Copy link

ArvidAnderson commented Oct 27, 2023

I also experience the same issue, downgrading MSAL Browser to 3.2.0 solved it

@baseloncohost
Copy link
Author

@konstantin-msft same experience with latest bits. Downgraded to msal-browser 3.2.0 fixes this. Any chance this has something to do with how the Application has to be instantiated?

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/v2-migration.md#application-instantiation

I don't think it's related since the demo already has a call for msalInstance.initialize() =>

export const msalInstance = new PublicClientApplication(msalConfig);

msalInstance.initialize().then(() => {
    // Account selection logic is app dependent. Adjust as needed for different use cases.
    const accounts = msalInstance.getAllAccounts();
    if (accounts.length > 0) {
        msalInstance.setActiveAccount(accounts[0]);
    }

    msalInstance.addEventCallback((event: EventMessage) => {
        if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
            const payload = event.payload as AuthenticationResult;
            const account = payload.account;
            msalInstance.setActiveAccount(account);
        }
    });

    const root = ReactDOM.createRoot(
        document.getElementById("root") as HTMLElement
    );
    root.render(
        <Router>
            <ThemeProvider theme={theme}>
                <App pca={msalInstance} />
            </ThemeProvider>
        </Router>
    );
});

@hectormmg
Copy link
Member

@baseloncohost could you try adding your cloudDiscoveryMetadata to your MSAL auth config as explained in this doc and see if that resolves your issue as a temporary workaround. If it does resolve your issue, that means #6602 is in fact the root cause and we can focus on fixing that for the next release. Thanks

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 27, 2023
@baseloncohost
Copy link
Author

@baseloncohost could you try adding your cloudDiscoveryMetadata to your MSAL auth config as explained in this doc and see if that resolves your issue as a temporary workaround. If it does resolve your issue, that means #6602 is in fact the root cause and we can focus on fixing that for the next release. Thanks

I can confirm the suggested workaround does indeed work correctly, tested on both the sample project and my private project.

versions install:

├── @azure/msal-browser@3.3.0
├── @azure/msal-react@2.0.5

For now I will be using @azure/msal-browser@3.2.0 to mitigate the additional HTTP request upon initialization.

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 Awaiting response from the MSAL.js team and removed Needs: Author Feedback Awaiting response from issue author labels Oct 27, 2023
@hectormmg
Copy link
Member

hectormmg commented Oct 27, 2023

@baseloncohost one more test, I think I was able to repro your use-case. Can you make sure your knownAuthorities value is correct? I see you have the same value (which I assume is the entire authority URL) for the authority and the knownAuthorities, but knownAuthorities should only include the domain:

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/authority.md#azure-ad-b2c

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 27, 2023
@baseloncohost
Copy link
Author

@baseloncohost one more test, I think I was able to repro your use-case. Can you make sure your knownAuthorities value is correct? I see you have the same value (which I assume is the entire authority URL) for the authority and the knownAuthorities, but knownAuthorities should only include the domain:

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/authority.md#azure-ad-b2c

I see what you mean, but it was probably a bad copy paste by me on the original post.. my current config is as follows:

auth: {
    clientId: process.env.AZURE_CLIENT_ID ?? '',
    authority: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}`,
    // authority domain translates to the following in my env file => <tenant-name>.onmicrosoft.com
    knownAuthorities: [b2cPolicies.authorityDomain ?? ''], 
    redirectUri: '/',
    postLogoutRedirectUri: '/auth/login',
    navigateToLoginRequestUrl: false,
},

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 Awaiting response from the MSAL.js team and removed Needs: Author Feedback Awaiting response from issue author labels Oct 27, 2023
@hectormmg
Copy link
Member

@baseloncohost that's odd, if you're using an AAD authority then even before endpoints are resolved MSAL should be able to match the ID token because AAD authorities are included in the hardcoded metadata shipped with MSAL. I'll keep looking into it and update the thread when I know more.

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Author Feedback Awaiting response from issue author and removed Needs: Attention 👋 Awaiting response from the MSAL.js team labels Oct 27, 2023
@hectormmg
Copy link
Member

Ok, I see the issue. Tenanted authorities won't find a match in hardcoded metadata, which is why even AAD authorities are failing in this case. We'll figure out a fix and update this thread when the PR is ready. Thanks everyone.

hectormmg added a commit that referenced this issue Oct 30, 2023
This PR:
- Updates hardcoded Cloud Discovery Metadata to the correct value from
the network response
- Returns a cached account without ID token claims if the matching ID
token cannot be found
- Adds end-to-end tests for AAD tenanted authorities
- Fixes #6608  and #6602
@microsoft-github-policy-service microsoft-github-policy-service bot removed the Needs: Author Feedback Awaiting response from issue author label Oct 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
b2c Related to Azure B2C library-specific issues bug-unconfirmed A reported bug that needs to be investigated and confirmed msal-browser Related to msal-browser package msal-react Related to @azure/msal-react public-client Issues regarding PublicClientApplications question Customer is asking for a clarification, use case or information.
Projects
None yet
11 participants