How do I create an authentication layer without public routes (React)?

Hey, I followed this tutorial.

I’m now wondering how I create an authentication layer around my whole application instead of displaying any public routes like the tutorial has.

I have tried authenticating my app by doing the following:

import * as React from "react";
import { Route, RouteComponentProps } from "react-router";
import { Router } from "react-router-dom";
import { WebAuthentication } from "./auth/WebAuthentication";
import App from "./master/App";
import Callback from "./master/Callback";
import history from "./services/history";

const auth = new WebAuthentication();

const handleAuthentication = (props: RouteComponentProps<{}>) => {
  if (/access_token|id_token|error/.test(location.hash)) {
    auth.handleAuthentication();
  }
};

const Routes: React.SFC = () => {
  return (
    <Router history={history}>
      <main role="main">
        {auth.authenticated ? (
          <Route path="/" render={props => <App auth={auth} {...props} />} />
        ) : (
          auth.login()
        )}
        <Route
          path="/callback"
          render={props => {
            handleAuthentication(props);
            return <Callback {...props} />;
          }}
        />
      </main>
    </Router>
  );
};
export default Routes;

When the application loads in the browser it redirects to the Auth0 login page, when I login I am then redirected back to my application, then I’m redirected back to the Auth0 login page again. When I login for the second time the application loads correctly.

The auth.authenticated method returns false because I’m guessing the handleAuthentication method hasn’t finished running when this conditional statement is ran:

{auth.authenticated ? (
  <Route path="/" render={props => <App auth={auth} {...props} />} />
) : (
  auth.login()
)}

It seems to be very hard just to get my whole application authenticated. Can anybody show me an example of a React application that uses Auth0 but has no public routes, or let me know where I am going wrong in my example?

Thanks

Hey there!

Sorry for such delay in response! We’re doing our best in providing the best developer support experience out there, but sometimes the number of incoming questions is just too big for our bandwidth. Sorry for such inconvenience!

Do you still require further assistance from us?