Skip to content

fix(web): send a signed-out user to sign in when an API call hits the SWA 401 redirect - #86

Merged
MWG-Logan merged 2 commits into
devfrom
fix/51-session-expired-sign-in
Oct 3, 2026
Merged

MWG-Logan merged 2 commits into
devfrom
fix/51-session-expired-sign-in

Conversation

@mwg-bender

@mwg-bender mwg-bender Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When the session has expired, an API call from the Web app now sends the user to sign in and back to the page they were on, instead of leaving them with an error. An authenticated user without the admin role now gets a short 403 page with a sign-out link instead of a sign-in loop. Signed-in admins see no change. Nothing in the API changed; access control stays in the SWA route table.

What #73 already covered vs what this adds

From the issue: (a) the opaque cross-origin failure, (b) an automatic navigation instead of a message, (c) the explanatory 403 page.

#73 (ApiResult.cs) already had:

  • SessionExpiredMessage, SignInUrl(returnPath) and IsSessionExpired(message);
  • a 401 mapped to "Your session expired. Sign in again.";
  • a 200 text/html answer from /api/* treated as session expired (the browser followed the SWA redirect and got the sign-in page);
  • a "Sign in" link beside that message (ApiErrorBar).

It did not cover (a), (b) or (c). This PR adds:

  • (a) and (b): SessionExpiredHandler, a DelegatingHandler on the Web HttpClient. It does a forced navigation to sign-in for a 401, for a followed redirect to /.auth/..., for a 200 text/html answer, and for an opaque transport failure when SWA confirms that nobody is signed in.
  • (c): wwwroot/403.html and a 403 responseOverrides entry.

The messages from #73 and the sign-in link are unchanged. They still show if the navigation does not happen, for example during an outage.

Small deviation from the issue text: the issue says "navigates to /login". The handler navigates to ApiResult.SignInUrl(<current path>), which is /.auth/login/aad?post_login_redirect_uri=<current path>. /login rewrites to the same /.auth/login/aad route, but it carries no return path. Using SignInUrl brings the user back to the page they were on, and it is the URL the existing "Sign in" link already uses.

Security review notes (for Woody)

Every changed line of staticwebapp.config.json (inside responseOverrides; nothing else in the file changed):

     "401": {
       "redirect": "/.auth/login/aad?post_login_redirect_uri=.referrer",
       "statusCode": 302
-    }
+    },
+    "403": {
+      "rewrite": "/403.html"
+    }

The routes array is unchanged: * and /api/* still require admin, /logout still redirects to /.auth/logout with no role, /login still rewrites to /.auth/login/aad, and /.auth/login/github still answers 404. The 401 override is byte-for-byte the same. navigationFallback is unchanged. A rewrite override keeps the 403 status and only replaces the body. No statusCode is set on it, so the status is not turned into 200.

Who gets what, before and after:

Who Before After
Signed out, page navigation (/, /games) 401, which the 401 override turns into a 302 to sign-in Same (unchanged)
Signed out (session expired), API call from the open app Error message: "Could not reach the server" for the opaque failure, or "Your session expired" with a sign-in link (#73) Forced navigation to /.auth/login/aad?post_login_redirect_uri=<current page>; after sign-in the user is back on that page
Signed in, not admin, page navigation 403 with SWA's default error page 403 with /403.html: "You are signed in, but this account is not allowed to use Event Manager", plus a link to /logout
Signed in, not admin, /api/* 403 403, now with the /403.html body. No data either way
Admin App and API work Same: the handler passes every successful JSON answer and every 400/403/404/500 through untouched

Why the outage probe exists. In production, an expired session's /api/* call is redirected to the identity provider's host, so the browser's fetch fails with an opaque network error. That error looks exactly the same as the API or the network being down. Before navigating on that case only, the handler calls SWA's built-in GET /.auth/me on the page's own origin. It treats the user as signed out only when that call succeeds with {"clientPrincipal": null}. In every other case it rethrows the original exception unchanged, and the page shows "Could not reach the server" exactly as before: the probe fails too (outage), answers an error status, returns something that is not JSON, or returns a principal (still signed in, so this is a real network problem). This way an outage never sends a signed-in user through a sign-in loop.

Why no API auth was added. By design every API HTTP trigger is AuthorizationLevel.Anonymous. The Function App is a bring-your-own backend linked to the SWA, and the SWA route table enforces the admin role. This PR changes only the Web client and the SWA config. The handler adds no credentials, no headers and no auth logic to any request. It only reads responses and decides whether to navigate.

Loop guards. The handler navigates at most once per page load: one flag per handler instance, and the forced load starts a fresh app. It never navigates for the /.auth/me probe itself, because that request bypasses the /api/ filter and goes straight to the inner handler. It never probes or navigates for a cancellation or the client's 30 second timeout (OperationCanceledException). After the first navigation, later opaque failures are not probed again.

403 page. It is static HTML with an inline <style> and nothing else: no script, no external request, no data. It is served only through the 403 override. A direct GET /403.html still falls under * and needs admin, like every other file.

Change

  • MW-GC.EventManager.Web/Services/SessionExpiredHandler.cs (new): the DelegatingHandler described above. It handles only requests whose path starts with /api/.
  • MW-GC.EventManager.Web/Program.cs: the scoped HttpClient is built on SessionExpiredHandler → HttpClientHandler. BaseAddress and the 30 second Timeout are unchanged.
  • MW-GC.EventManager.Web/wwwroot/403.html (new): the plain 403 page.
  • MW-GC.EventManager.Web/staticwebapp.config.json: the 403 override above.
  • MW-GC.EventManager.Web.Tests/SessionExpiredHandlerTests.cs (new): 16 test methods, 19 test cases. They use a fake inner handler and a recording NavigationManager.

ApiResult.cs, the pages, API/, Shared/ and .github/ are untouched.

Validation

All runs by the worker (Nerd Bender's Kanban worker) on this machine. Every build was cold (bin/ and obj/ deleted first).

Errors Warnings Api.Tests Web.Tests Total
Baseline, dev d5e5476 (card tip) 0 0 254 188 442
After, on d5e5476 0 0 254 207 461 = 442 + 19
After, rebased on dev d24ab2e (final head) 0 0 254 212 466 = 447 + 19

dev moved from d5e5476 to d24ab2e (#84) during the work. #84 touches CONTEXT.md, Events.razor and EditEventSnapshotTests.cs, none of them in this PR, so the rebase was clean. #84 added 5 Web tests, which makes dev 447 (254 + 193, per Nerd's #84 validation). No failed tests and no warning code before or after.

New tests (Web.Tests, SessionExpiredHandlerTests):

  • UnauthorizedOnAnApiCallSendsTheUserToSignInOnce
  • SignInReturnsToTheCurrentPathAndQuery
  • ApiCallThatFollowedARedirectToTheSignInRouteSendsTheUserToSignIn
  • ApiCallAnsweredWithTheSignInPageAsHtmlSendsTheUserToSignIn
  • OpaqueFailureWhileSignedOutSendsTheUserToSignInAndRethrows
  • OpaqueFailureWhenTheSignInCheckAlsoFailsIsAnOutageAndDoesNotNavigate
  • OpaqueFailureWhenTheSignInCheckAnswersAnErrorStatusDoesNotNavigate
  • OpaqueFailureWhileStillSignedInDoesNotNavigate
  • OpaqueFailureWhenTheSignInCheckIsNotJsonDoesNotNavigate
  • TimeoutIsNotTreatedAsASignOut
  • NonApiRequestIsPassedThroughUntouched
  • NonApiTransportFailureIsNotProbed
  • TwoFailingCallsNavigateOnlyOnce
  • OpaqueFailureAfterTheNavigationIsNotProbedAgain
  • OtherApiFailureStatusIsPassedThroughUntouched (404, 500, 403, 400)
  • SuccessfulApiJsonIsPassedThroughUntouched

Running stack (with-stack.sh: Azurite + API + Web + SWA CLI 2.0.10 on http://127.0.0.1:4280, Release web build behind SWA), on the final head a62b445:

  • api_flows.py: 10/10 passed.
  • Auth flow script, redirects not followed: 16/16 passed.
Request Status Relevant headers / body
signed out GET /api/games 302 Location: /.auth/login/aad?post_login_redirect_uri=%2Fapi%2Fgames, Content-Length: 0 (the response the client must handle)
signed out, following that Location 200 Content-Type: text/html, the emulator's sign-in page (the case #73 and the handler's text/html check cover)
signed out GET /.auth/me 200 {"clientPrincipal":null} (what the outage probe looks for)
signed out GET /logout 302 Location: http://127.0.0.1:4280/.auth/logout
signed out GET / 302 Location: /.auth/login/aad?post_login_redirect_uri=%2F (401 override unchanged)
non-admin GET /.auth/me 200 principal with roles anonymous, authenticated
non-admin GET /, GET /games, GET /api/games 302 to sign-in, no app and no data (emulator limitation, see below)
non-admin GET /logout 302 Location: http://127.0.0.1:4280/.auth/logout (reachable without admin)
admin GET /api/games 200 application/json; charset=utf-8, game list (unchanged)
admin GET /, GET /games 200 the app's index.html (unchanged)
admin GET /403.html 200 the published page: "You are signed in, but this account is not allowed to use Event Manager.", <a href="/logout">, no <script>, no external URL

Emulator limitation: the non-admin 403 cannot be shown live. SWA CLI 2.0.10 answers a signed-in user whose roles do not match with 401, not 403. In dist/msha/routes-engine/rules/routes.js, isRouteRequiringUserRolesCheck returns false both for "no cookie" and for "roles don't match", and dist/msha/middlewares/request.middleware.js then always calls handleErrorPage(401). The 401 override then redirects to sign-in. Production SWA returns 403 for an authenticated user without the role, which is what the new override handles. What could be verified instead:

  1. the SWA CLI's own schema validator accepts the new config;
  2. the SWA CLI's own responseOverrides engine, given this config, turns a 403 into status 403 with the body rewritten to swa://403.html, and still turns a 401 into a 302 to /.auth/login/aad?post_login_redirect_uri=%2Fgames;
  3. the page is published and served (table above);
  4. /logout is reachable for a non-admin.

CI check-runs on the final head a62b445 (read back after the push): build-and-test success, CodeQL success, Analyze (actions) success, Analyze (csharp) success, Analyze (javascript-typescript) success, submit-nuget success (6/6).

Not run:

  • UI flow NOT RUN: the browser following the sign-in after an expired session, and a non-admin seeing the 403 page in a browser. The worker has no browser tool. Nerd runs these at validation.
  • The production cross-origin case (a fetch that ends on the identity provider's host and fails opaquely) cannot happen against the emulator, because its sign-in page is same-origin. It is covered by the unit tests only.

Notes

… SWA 401 redirect

When the session has expired, Static Web Apps answers an /api/* call with a
302 to its sign-in route. Depending on where the browser's fetch ends up, the
Web app saw a 401, the sign-in page as 200 text/html, or (once the redirect
reaches the identity provider's host) an opaque network failure. #73 already
turned the first two into a "session expired" message with a sign-in link; the
third still showed "Could not reach the server", and none of them took the
user to sign in.

Add SessionExpiredHandler, a DelegatingHandler on the Web HttpClient that only
looks at requests whose path starts with /api/. A 401, a response whose final
URL is under /.auth/ and a 200 text/html answer are treated as session
expired. An opaque HttpRequestException (not a cancellation or the 30 second
timeout) is treated as session expired only when SWA's own GET /.auth/me
answers with clientPrincipal null, so an outage still shows the unreachable
message. On session expired the handler does a forced navigation to
ApiResult.SignInUrl(<current page>), at most once per page load, and returns
the original response or rethrows the original exception unchanged.

An authenticated user without the admin role now gets wwwroot/403.html (a
plain page with a /logout link) through a new 403 responseOverride. The 401
override and the route table (`*` and `/api/*` require admin) are unchanged,
and no auth is added to the API.

Closes #51
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Summary

Tests 📝 Passed ✅ Failed ❌ Skipped ⏭️ Other ❓ Flaky 🍂 Duration ⏱️
404 404 0 0 0 0 7.8s

🎉 No failed tests in this run.

Github Test Reporter by CTRF 💚

🔄 This comment has been updated

@mwg-bender

mwg-bender Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Independent validation by Nerd Bender (head 92f3399)

dev moved from d24ab2e to 6477a46 (#85) while this PR was open, so I brought the branch up to date with dev (the Merge branch 'dev' commit, expected head SHA supplied) and validated that exact head, not the worker's a62b445. The merge changed no file in this PR (5 files, same as before).

Cold build and tests (clean bin/ and obj/): 0 errors, 0 warnings. Api.Tests 182 passed, Web.Tests 222 passed (203 on dev + 19 new), 0 failed.

CI on 92f3399: build-and-test, CodeQL, Analyze (actions, csharp, javascript-typescript) and submit-nuget all success.

Running stack (Azurite + API + Web + SWA CLI, Release web build behind SWA on 4280):

  • api_flows.py: 10/10.
  • Expired session, in a real browser. Signed in as admin, loaded /events (list rendered), then deleted the StaticWebAppsAuthCookie and clicked the Games nav link. Within 1.5 s the page navigated to /.auth/login/aad?post_login_redirect_uri=%2Fgames. The return path is the page the user was on (/games), not /api/games, which is what a direct signed-out API call gives. That is SessionExpiredHandler building ApiResult.SignInUrl(<current path>).
  • Admin unaffected. With an admin cookie, /games loads in the app.
  • /403.html is published and served to an admin: the heading "You are signed in, but this account is not allowed to use Event Manager.", a <a href="/logout"> link, and no <script> element.

Not run, and why

  • The non-admin 403 in a browser. The SWA CLI emulator answers a signed-in user without the role with 401, not 403 (the worker's source reading of routes.js and request.middleware.js explains it; I did not re-read it). Production SWA returns 403, and I could not show that live. The 403 responseOverrides entry is covered only by the schema check and the emulator's override engine, per the PR body.
  • Completing the sign-in and landing back on /games. In the automated browser, submitting the emulator's sign-in form (a real click on Login and requestSubmit()) did not navigate away, so I could not watch the return trip. I did not look into why. The post_login_redirect_uri carrying /games is the part I confirmed.
  • The production cross-origin case (the sign-in redirect ending on the identity provider's host, so the fetch fails with an opaque error). The emulator's sign-in page is same-origin, so this is unit-tested only, in OpaqueFailure* tests.
  • ui_flows.mjs (the headless UI script). I did not run it on this head. It already fails 8/9 on dev for an unrelated reason (a name-field selector in my script), so it would add nothing.
  • Whether the Games list finished loading as admin. I read the page text early and it still said "Loading games...". I did not wait and re-read, so I only know the page and its shell loaded.

Diff read. SessionExpiredHandler navigates at most once per page load, only for /api/ requests, and rethrows the original exception. The /.auth/me outage probe returns "signed out" only for a 200 with clientPrincipal: null, so an outage does not send a signed-in user through a sign-in loop. The config change is the single 403 rewrite override. No API auth was added, which matches the design (the SWA route table enforces admin).

Milestone set to 0.3.0. Requesting review from @MWG-Logan: this touches auth behaviour and staticwebapp.config.json, so it is outside the merge grant. I am not merging it.

@mwg-bender mwg-bender Bot added this to the 0.3.0 milestone Oct 3, 2026
@mwg-bender
mwg-bender Bot requested a review from MWG-Logan October 3, 2026 21:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant