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

How to secure whole application - not only selected routes?

Open safjanowski opened this issue 1 year ago • 0 comments

I want to secure whole application - navigation, routes and footer and as long as user is not authorised should not be present. One loading component should be rendered during checking if user is authorised - if not - lets redirect him / her to external login page After user back - ideally would be to display whole application (now for a moment Loading component is rendered twice)

Example repository: https://github.com/safjanowski/musical-train

App.tsx

<Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
  <SecuredApp>
    <Nav />
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="*" element={<div>404 Not Found</div>} />
    </Routes>
    <Footer />
  </SecuredApp>
  <Routes>
    <Route
      path="/login/callback"
      element={
        <LoginCallback
          loadingElement={<Loading from={"login callback"} />}
        />
      }
    />
  </Routes>
</Security>

SecuredApp.tsx

const SecuredApp: FC<{ children: ReactNode }> = ({ children }) => {
  const { authState } = useOktaAuth();

  useEffect(() => {
    if (!authState) {
      return;
    }

    if (!authState.isAuthenticated) {
      const originalUri = toRelativeUrl(
        window.location.href,
        window.location.origin,
      );
      oktaAuth.setOriginalUri(originalUri);
      oktaAuth.signInWithRedirect();
    }
  }, [authState]);

  if (!authState || !authState.isAuthenticated) {
    return <Loading from={"secured app"} />;
  }

  return <>{children}</>;
};

Dependencies:

  • "@okta/okta-auth-js": "^7.9.0",
  • "@okta/okta-react": "^6.9.0",
  • "react": "^18.3.1",
  • "react-dom": "^18.3.1",
  • "react-router-dom": "^6.2.1"

User is redirected to external login page, redirected to application, redirected to external login page. Even if Okta is asking about push notification - without approving it - user is able to open application in browser and will be authenticated.

safjanowski avatar Jan 29 '25 15:01 safjanowski