Can't access a react protected route using URL

I would like to access a react protected route when logged in. When I use a button to do so, it works but I can’t access the route using the URL.

Here is how it works :

  • If a user is connected : he can access his account page using a button in the header (or using the URL)
  • If a user is not connected : he gets redirected to auth0 login page and then returns to ‘/user’ route.

Here is the issue :
After connection, the user gets redirected to ‘/user’ route but the home page is rendered. Whereas if I use the button in the header, it works perfectly fine.

const AuthenticationGuard = ({component}) => {
    const AuthenticatedComponent = withAuthenticationRequired(component, {
        onRedirecting: () => <PageLoader/>,
    });
    return <AuthenticatedComponent/>;
};

export default AuthenticationGuard;

This is the AuthenticationGuard as it is given in the documentation.

 <BrowserRouter>
      <Auth0Provider
          domain={domain}
          clientId={clientId}
          authorizationParams={{
            redirect_uri: window.location.origin
          }}
      >
        <Routes>
           <Route path="/" element={<Home/>}/>
           <Route path="/user" element={<AuthenticationGuard component={UserAccount}/>}/>
        </Routes>
      </Auth0Provider>
</BrowserRouter>

use of Routes and Auth0Provider

<Link to="/user">
      <div className="my-3 mx-5 w-full h-full hover:underline">
            My account
      </div>
</Link>

if the user uses this link, he can go /user route as expected if he is connected.
I’m new in using Auth0 and manipulating authentication. I have no clue how to solve it.

Hi @sprwalrus,

Welcome to the Auth0 Community!

The app is redirecting to the home page after login because of window.location.origin being set as the redirect_uri in authorizationParams. You can try setting the redirect_uri to the /users route. Alternatively, you can try the below adjustment to the AuthenticationGuard code.

The withAuthenticationRequired takes the component you want to protect and a configuration object to customize the auth flow. You are already using the onRedirecting property. There’s another property you can use here: returnTo. This property lets you specify a path for React to redirect a user after the login transaction that the user triggered in this component completes.

Example:

const AuthenticationGuard = ({component}) => {
    const AuthenticatedComponent = withAuthenticationRequired(component, {
        onRedirecting: () => <PageLoader/>,
        returnTo: '/users'
    });
    return <AuthenticatedComponent/>;
};

export default AuthenticationGuard;

Here is a helpful guide to all things React: React Router 6 Code Sample: Basic Authentication

Info on Route Guards in React: React Authentication By Example: Using React Router 6

I hope this helps!

Best,

Mary Beth

Hi @marybeth.hunter,

(sorry for all the posts deleted I could remember how to add long portions of code)

Thank you very much for the time you spent to reply.

Unfortunately, it didn’t fix my problem. But I found another answer which led me to add the onRedirectCallback prop it almost fixed it.

Actually, I can now be redirected to my /user route but I seems that auth0 goes first to /user then goes to root route but holding some code and state property in URL.
Like so : /?code=[value]&state=[value]%3D%3D.
And then it goes back to /user route.

In history route I have successively :

  • /user
  • /?code=[value]&state=[value]%3D%3D
  • /user

Have you got any idea of what that it ?

const Auth0ProviderWithRedirectCallback = ({ children, ...props }) => {
  const navigate = useNavigate();
  const onRedirectCallback = (appState) => {
    navigate((appState && appState.returnTo) || window.location.pathname);
  };
  return (
    <Auth0Provider onRedirectCallback={onRedirectCallback} {...props}>
      {children}
    </Auth0Provider>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Auth0ProviderWithRedirectCallback
        domain={domain}
        clientId={clientId}
        authorizationParams={{
          redirect_uri: window.location.origin
        }}
      >
        <App />
      </Auth0ProviderWithRedirectCallback>
    </BrowserRouter>
  </React.StrictMode>
);

Thank you in advance

Hi @sprwalrus,

Can you confirm that you are now being redirected to /users after login?

Regarding your question about the code=[value], this is expected. This is the response received after making a successful /authorize request. Please see this link for more info on this: Add Login Using the Authorization Code Flow with PKCE

Best,

Mary Beth

Hi,
yes I am redirected to ‘/user’ after I login.
I added {replace: true} in theonRedirectCallback props like this so the root path doesn’t stack anymore:

const Auth0ProviderWithRedirectCallback = ({ children, ...props }) => {
  const navigate = useNavigate();
  const onRedirectCallback = (appState) => {
    navigate(appState?.returnTo || window.location.pathname, { replace: true }); // here
  };
  return (
    <Auth0Provider onRedirectCallback={onRedirectCallback} {...props}>
      {children}
    </Auth0Provider>
  );
};

Now, after logging in, the history stack looks like this :

  • 1 - Initial route from where I want to access /user
  • 2 - after login : /user path
  • 3 - /user path again and it

If I click the arrow to go back to the first /user path in history, it renders the loading page and doesn’t no redirect.

1 Like