gwrik09
gwrik09

Reputation: 191

Issues with Protected Routes on Initial Load and Refresh

I am working onReact application wutg Azure Static Web Apps. My goal is to configure path such that some pages are accessible without authentication via direct link maybe as Anonymous user, while others require users to log in. Authentication is already set up using Azure B2C, and the login flow works as expected. I expected staticwebapp.config.json would do the whole job.

Here’s a snippet of my current staticwebapp.config.json configuration:

{
  ... B2C part....
  "routes": [
  ...login/logout routes...
    {
      "route": "/platform/*",
      "allowedRoles": ["authenticated"]
    }
  ],
  "navigationFallback": {
    "rewrite": "index.html",
  },
  "responseOverrides": {
    "401": {
      "redirect": "/login",
      "statusCode": 302
    }
  },
  "globalHeaders": {
    "content-security-policy": "default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'"
  },
  "mimeTypes": {
    ".json": "text/json"
  }
}

Issue: When navigating to XXXX.com, I want unauthenticated users to be redirected to /platform/dashboard. However, the protected <Dashboard /> content is displayed even if the user is not authenticated. Similarly, when running the app locally (e.g., localhost:4000/), the unauthenticated user can land on the protected <Dashboard /> route somehow. However, if the page is refreshed, the app correctly redirects to the login page.

I also noticed a similar behavior with navigation links created using react-router-dom’s <Link to={path} />. To make navigation secure, I had to use window.location.assign(path) instead in the navbar implementation.

app.tsx

...
<BrowserRouter>
  <Routes>
    {/* Public pages */}
    <Route element={<PublicPageParent />}>
      <Route path="/public/details" element={<SomeComponent />} />
      <Route path="/report" element={<ReportComponent />} />
    </Route>

    {/* Protected routes */}
    <Route path="/platform/dashboard" element={<Dashboard />} />
    <Route path="/platform/users" element={<Users />} />

    {/* Default redirection */}
    <Route path="/" element={<Navigate to="/platform/dashboard" />} />
  </Routes>
</BrowserRouter>

Questions:

  1. Why does the <Dashboard /> component render without authentication when first loaded, but redirects correctly after a refresh?
  2. How can I ensure protected routes are only accessible after proper authentication, even on the first load?
  3. Is there a better way to handle navigation securely with react-router-dom and azure static webapp without relying on window.location.assign?

Any advice or guidance would be greatly appreciated!

Upvotes: 1

Views: 28

Answers (0)

Related Questions