auth0-react icon indicating copy to clipboard operation
auth0-react copied to clipboard

Race condition between isAuthenticated and isLoading (redirects) (react-router-v6)

Open kress92cs opened this issue 4 years ago • 24 comments

Hello guys!

We have a application with auth0 and react-router v6 and we stumbled upon something that looks like a race condition with onRedirectCallback

  const ProtectedRoute = withAuthenticationRequired(Component, {
    onRedirecting: () => <OurLoadingPage />,
    loginOptions: {
      acr_values: auth0Config.acrValues,
    }
  });

-----------------------------------------------------------------------------------------------------------


  const Auth0Example = ({ props }) => {
   const navigate = useNavigate();

  const onRedirectCallback = appState => {
    navigate(appState?.returnTo || window.location.pathname);
  };

  return (
    <Auth0Provider
    {...auth0Config}
    redirectUri={window.location.origin}
    onRedirectCallback={onRedirectCallback}
    >
    {children}
  </Auth0Provider>
  )
}

This causes us to have a infinite login loop because isLoading is set to false and isAuthenticated is not yet true. (cookie not yet set)

If we add

  const onRedirectCallback = appState => {
  setTimeout(navigate(appState?.returnTo || window.location.pathname), 3000);
};

It will work. (this is not a option because we dont want timeouts in our code)

Or if we remove the onRedirectCallback, but then it wont navigate correctly. (get a blank page without the rendering of component)

isLoading TRUE isAuthenticated FALSE
isLoading FALSE isAuthenticated FALSE
isLoading FALSE isAuthenticated TRUE

Should there be a flag that hold the state of a cookie is set or not before redirecting?

also noted here:

https://github.com/auth0/auth0-react/issues/82#issuecomment-672853184

Thanks in advance. And have a lovely day :)

kress92cs avatar Mar 24 '22 09:03 kress92cs

I have a similar case — along with onRedirectCallback={(appState) => { navigate(appState?.returnTo || window.location.pathname, { replace: true }); }} I also have a redirect from root to a protected route (i.e. <Route element={<Navigate replace={true} to={{ pathname: "/hives" }} />} exact={true} path="/" />) deeper in the components tree within the component that isn't rendered up until isLoading is true. However, when the flag indeed becomes true and the aforementioned redirect happens, more often than not the user is not authenticated yet, so withAuthenticationRequired that protectes the /hives route redirects to the login dialog, from there returns to /?code=...&state=..., and before auth0-react can authenticate the user the Navigate to the protected route is being rendered again and, given that the user is not authenticated, it goes to the login dialog again. So it seems like I cannot rely on isLoading flag as an indication that the user has been correctly processed 🤔. If I remove the redirect from / to /hives it all works, tho.

volodymyr-kushnir avatar Mar 27 '22 21:03 volodymyr-kushnir

I have a similar case — along with ....

Yes, this seems to be the same problem :)

kress92cs avatar Mar 28 '22 07:03 kress92cs

Hi @kress92cs - thanks for raising this

I can't see anything wrong with the code you've shared, and can't reproduce the issue on the example app - could you create a simple repo that demonstrates the issue?

adamjmcgrath avatar Mar 29 '22 13:03 adamjmcgrath

Hello and thanks for the reply. Will do :)

kress92cs avatar Mar 30 '22 07:03 kress92cs

Same issue with a useEffect approach, and same solution.

image

awdyson avatar Apr 06 '22 19:04 awdyson

Experiencing the same issue where isLoading is false but isAuthenticated is also still false and becomes true after. I'm doing this inside of a useEffect similar to @awdyson

Created a repo using CRA to show example here

Also worth mentioning - this only happens after the redirect. Refreshing the page with a logged in account works as expected.

Initial redirect after logging in with google: Screenshot 2022-04-20 at 15 33 47

Then after I refresh the page: Screenshot 2022-04-20 at 15 34 07

bethcarslaw avatar Apr 20 '22 14:04 bethcarslaw

I have a similar issue, but I don't know if this is because react 18 or react-location (we have another app with react 17 and reac-router v5 which works perfectly fine).

So instead of using withAuthenticationRequired, I did the following work-around (inspired from above comments - thank you all ^^):

  useEffect(() => {
    ;(async () => {
      try {
        // There's a race condition somewhere: the user is not authenticated immediately
        // See https://github.com/auth0/auth0-react/issues/343
        await new Promise(r => setTimeout(r, 1000)) // sleeping 1s seems fine
        await getAccessTokenSilently()
      } catch (e) {
        loginWithRedirect()
      }
    })()
  }, [getAccessTokenSilently, loginWithRedirect])

vcarel avatar Apr 25 '22 14:04 vcarel

Facing this same issue, ended up here after reading through https://github.com/auth0/auth0-react/issues/82

We've tried all suggested "solutions" but nothing has worked for us. Private repo so unfortunately I cannot share the code base.

just-Bri avatar Apr 26 '22 18:04 just-Bri

@just-Bri might it be that the response time is too slow? What happens when you add an obscene timeout length to one of these solutions? Also, I'd add a couple log statements to make sure your code is running at the time you expect it to run at.

awdyson avatar Apr 26 '22 21:04 awdyson

@awdyson Technically adding a timeout of ~5 seconds will make it work but that's not a viable solution, that's a hack at best.

I can clearly see in my logs that isAuthenticated and isLoading do not correspond correctly. isAuthenticated gets set to true => events trigger(useEffects) but isLoading is still false which means those useEffects do different operations.

EDIT: put true/false in the wrong spots. Those 2 words are losing meaning for me today haha

just-Bri avatar Apr 26 '22 21:04 just-Bri

Technically adding a timeout of ~5 seconds will make it work but that's not a viable solution, that's a hack at best.

100% agree. I'm not seeing movement in this thread toward a solution though 😕

awdyson avatar Apr 26 '22 22:04 awdyson

Facing this same issue, ended up here after reading through https://github.com/auth0/auth0-react/issues/82

We've tried all suggested "solutions" but nothing has worked for us. Private repo so unfortunately I cannot share the code base.

My work around is checking the cookie set by auth0 rather than relying on isAuthenticated. I think it causes an extra redirect but it seems to work, at least for my app

bethcarslaw avatar Apr 26 '22 22:04 bethcarslaw

Facing the same

I have a similar issue, but I don't know if this is because react 18 or react-location (we have another app with react 17 and reac-router v5 which works perfectly fine).

So instead of using withAuthenticationRequired, I did the following work-around (inspired from above comments - thank you all ^^):

  useEffect(() => {
    ;(async () => {
      try {
        // There's a race condition somewhere: the user is not authenticated immediately
        // See https://github.com/auth0/auth0-react/issues/343
        await new Promise(r => setTimeout(r, 1000)) // sleeping 1s seems fine
        await getAccessTokenSilently()
      } catch (e) {
        loginWithRedirect()
      }
    })()
  }, [getAccessTokenSilently, loginWithRedirect])

This works for now, but is clearly also a hacky solution, and does not solve the overall problem.. The user is forced to wait for minimum 1 sec when the app checks whether the user is authenticated or not.

I think this is a major issue 😕

oskarthansen avatar Apr 27 '22 07:04 oskarthansen

Facing this same issue, ended up here after reading through #82 We've tried all suggested "solutions" but nothing has worked for us. Private repo so unfortunately I cannot share the code base.

My work around is checking the cookie set by auth0 rather than relying on isAuthenticated. I think it causes an extra redirect but it seems to work, at least for my app

@dalecarslaw this also sounds like a good temporary solution. But i can't find the cookie auth0 has set? Did you set the "tokenStorage" option, to store the token in cookies? In the documentation (https://auth0.com/docs/secure/security-guidance/data-security/token-storage), they say that "the default storage option is in-memory storage leveraging Web Workers". I can't figure out how to see if the token is set, when using that option.

oskarthansen avatar Apr 27 '22 07:04 oskarthansen

It seems like theres missing som "dispatches" in the source code.. If you see the "loginWithPopup" function, different dispatches are made, and sets whether the user is authenticated or not. Where the "loginWithRedirect" does not have any dispatches, and therefore does not set "isAuthenticated".

Have you guys tried with "loginWithPopup" and seen if that works?

My theory is that there should be added some extra code to the reducer, to set "isAuthenticated" after trying to login with "loginWithRedirect".

Am I missing something here?

The functions: image

The reducer: image

oskarthansen avatar Apr 27 '22 07:04 oskarthansen

Thanks for providing the example repro @dalecarslaw

I can confirm the issue, when the user returns to the app after login I'm seeing an unexpected state of isAuthenticated: false , isLoading: false

This looks like it's caused by the new behaviour of React 18 that double invokes things like setState in StrictMode to detect unexpected side effects (see https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)

This will only happen in development mode, and the workaround for now is to not use StrictMode - I can confirm that the example app @dalecarslaw shared works as expected if I remove the <StrictMode> component here https://github.com/dalecarslaw/auth0-issue/blob/master/src/index.tsx#L12

I'll prepare a fix as soon as I can and update this thread when it's available

adamjmcgrath avatar Apr 27 '22 11:04 adamjmcgrath

@adamjmcgrath Can't believe I forgot to mention this earlier, sorry! My project is on React 17 and react-router v5.

Will test out the prod build, and with(out) strict and update this comment.

just-Bri avatar Apr 27 '22 14:04 just-Bri

@adamjmcgrath Can't believe I forgot to mention this earlier, sorry! My project is on React 17 and react-router v5.

Will test out the prod build, and with(out) strict and update this comment.

@just-Bri Did this fix your issue? My team is in similar position (React v17, react-router v5-- but not using strict mode) and the latest version (@auth0/[email protected]) does not fix our issue (which happens in a production build). Upon initial login and being redirected, I still end up with a render where { isAuthenticated: false, isLoading: false } before a subsequent render results in isAuthenticated: true. Upon refreshing, this state doesn't occur.

Silverwolf90 avatar May 10 '22 21:05 Silverwolf90

I haven't gotten around to testing if strict mode helps. Will leave myself a reminder for tomorrow morning though!

just-Bri avatar May 10 '22 22:05 just-Bri

@just-Bri, StrictMode introduces a double-render for components as a way for React to smoke out performance issues and such. My understanding from @adamjmcgrath was that this double-render is what was causing an issue. Pretty sure adding StrictMode can only introduce issues.

@just-Bri and @Silverwolf90, It might be worth trying to move the AuthProvider as far up your React tree as you can. Here's the entry point for my application

function App() {
  // ...
  return (
    <StrictMode>
      <CookiesProvider>
        <ReduxProvider store={store}> {/* only because I store something from the JWT */}
          <AuthProvider>
            <LoginWrapper> {/* where my loginWithRedirect useEffect lives */}
              {/* below here are all my other context providers (including the router) and then the rest of my app */}

Disclaimer: I use a different router, but unless there's a serious bug with react-router, it shouldn't effect providers above it in the tree.

awdyson avatar May 10 '22 22:05 awdyson