Skip to content

How to secure whole application - not only selected routes? #291

Description

@safjanowski

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions