Check auth0 session when React SPA starts

Hey,

I am trying to solve this issue: I have 2 applications. One of them is React SPA (I am using @auth0/auth0-react). In this SPA, I am using localStorage to store user info in browser and I am using refresh tokens (not sure if this is relevant). If I log out in my other app, the localStorage in my SPA if not cleared (of course).

Problem: When user then visits my SPA, he is still logged in. :rotating_light:

I somehow need to check when SPA starts, that auth0 session is valid. Since there is no method checkSession, I tried doing:

useEffect(() => auth0.getAccessTokenSilently({ cacheMode: 'off' }), [])

but this ends up in infinite redirect loop, because it redirects to auth0, then it goes through login action flow, then I end up in my SPA again, and then useEffect callback is triggered again.

Thanks

To solve the issue of the user still being logged in when visiting your React SPA after logging out in the other app, you can try the following approach:

  1. Instead of relying on the localStorage for storing user info, consider using a more secure approach like storing the user session in an HTTP-only cookie. This way, the cookie will automatically be cleared when the user logs out in the other app.

  2. Implement a check on SPA startup to verify the validity of the Auth0 session. You can use the checkSession method provided by @auth0/auth0-react. This method will silently renew the user’s session if it is still valid, without causing an infinite redirect loop.

Here’s an example of how you can implement it:

import { useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

const App = () => {
  const { getAccessTokenSilently, isAuthenticated, loginWithRedirect } = useAuth0();

  useEffect(() => {
    const checkAuthSession = async () => {
      if (isAuthenticated) {
        try {
          await getAccessTokenSilently({ cacheMode: 'default' });
        } catch (error) {
          console.log('Error refreshing access token:', error);
          // Redirect the user to the login page
          loginWithRedirect();
        }
      }
    };

    checkAuthSession();
  }, [getAccessTokenSilently, isAuthenticated, loginWithRedirect]);

  // Rest of your app code

  return (
    // Your app components
  );
};

export default App;

To solve the issue of the user still being logged in when visiting your React SPA after logging out in the other app, you can try the following approach:

  1. Instead of relying on the localStorage for storing user info, consider using a more secure approach like storing the user session in an HTTP-only cookie. This way, the cookie will automatically be cleared when the user logs out in the other app.

  2. Implement a check on SPA startup to verify the validity of the Auth0 session. You can use the checkSession method provided by @auth0/auth0-react. This method will silently renew the user’s session if it is still valid, without causing an infinite redirect loop.

Here’s an example of how you can implement it:

javascript

Copy code

import { useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

const App = () => {
  const { getAccessTokenSilently, isAuthenticated, loginWithRedirect } = useAuth0();

  useEffect(() => {
    const checkAuthSession = async () => {
      if (isAuthenticated) {
        try {
          await getAccessTokenSilently({ cacheMode: 'default' });
        } catch (error) {
          console.log('Error refreshing access token:', error);
          // Redirect the user to the login page
          loginWithRedirect();
        }
      }
    };

    checkAuthSession();
  }, [getAccessTokenSilently, isAuthenticated, loginWithRedirect]);

  // Rest of your app code

  return (
    // Your app components
  );
};

export default App;

This code will check if the user is authenticated and then attempt to silently refresh the access token. If there’s an error refreshing the token, it will log the error and redirect the user to the login page.

Make sure you have the latest version of @auth0/auth0-react package installed and configured correctly in your React SPA

Do let me know how it goes :slight_smile:

1 Like

Hey, cacheMode can only have following values, no default.

Hey, You can leave to the ‘ON’ Mode.

Doc for the reference:

This package doesn’t expose any checkSession method

But leaving it on, it will not check the session. Instead, it will check that the item is present in localStorage, where it finds it and therefore doesn’t do request to auth0 to check session.

Alright I solved it by doing:

useEffect(() => {
        const runAsync = async () => {
              try {
                  await auth0.getAccessTokenSilently({
                      cacheMode: 'off',
                  });
              } catch {
                  auth0.loginWithRedirect();
              }
        };

        runAsync();
    }, []);
1 Like