bjerkio/oidc-react

not private route

marlena-sliwinska opened this issue · 3 comments

Hi, I've used oidc-react in my project.
As You can see I've wrapped my router with AuthProvider. (I am using react-router and new available API - createBrowserRouter)
<AuthProvider> <AppRouter /> </AuthProvider>

I want to exclude one of the routes from OAuth - make not restricted - available for all users, not only logged. Haw can I do that?
I cannot find it in documentation.
Is there any easy way?

@marlena-sliwinska I actually just went through this issue last week. In order to do it, you'll need to disable autoSignIn in your AuthProviderProps config. Then in your route configuration, you can do something like the following:

const AppRouter: React.FC = () => {
  const { isLoading, userData, signIn } = useAuth();
  
  const redirectToLogin = () => {
    if (!userData && !isLoading) {
      void signIn();
    }
  };
  
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/home"><Redirect to="/" /></Route>
        <Route path="/login"><Redirect to="/" /></Route>
        <Route path="/user-agreements" component={UserAgreements} />
        {userData && (
          <UserContainer.Provider>
            /* ...private routes here */
          </UserContainer.Provider>
        )}
        <Route render={redirectToLogin} />
      </Switch>
    </BrowserRouter>
  );
};

Essentially, if no userData exists, the user isn't logged in so the "private" routes won't even exist. If the page they attempt to access is one of the non-protected routes (at the top in this example), then it will route accordingly. If none of those match, then it falls through to the final universally matching Route which in turn redirects to the sign in page.

I am using the newest version of the react-router-dom and as you can see the implementation of routing looks like this:

import {
  createBrowserRouter,
  RouterProvider,
} from "react-router-dom";

import Root, { rootLoader } from "./routes/root";
import Team, { teamLoader } from "./routes/team";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    loader: rootLoader,
    children: [
      {
        path: "team",
        element: <Team />,
        loader: teamLoader,
      },
    ],
  },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
  <RouterProvider router={router} />
);

With this type of implementation is not so easy