Repository navigation
fix(web): send a signed-out user to sign in when an API call hits the SWA 401 redirect - #86
Conversation
… 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
Summary
🎉 No failed tests in this run. Github Test Reporter by CTRF 💚 🔄 This comment has been updated |
Independent validation by Nerd Bender (head
|
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
adminrole 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)andIsSessionExpired(message);text/htmlanswer from/api/*treated as session expired (the browser followed the SWA redirect and got the sign-in page);ApiErrorBar).It did not cover (a), (b) or (c). This PR adds:
SessionExpiredHandler, aDelegatingHandleron the WebHttpClient. It does a forced navigation to sign-in for a 401, for a followed redirect to/.auth/..., for a 200text/htmlanswer, and for an opaque transport failure when SWA confirms that nobody is signed in.wwwroot/403.htmland a 403responseOverridesentry.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 toApiResult.SignInUrl(<current path>), which is/.auth/login/aad?post_login_redirect_uri=<current path>./loginrewrites to the same/.auth/login/aadroute, but it carries no return path. UsingSignInUrlbrings 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(insideresponseOverrides; nothing else in the file changed):"401": { "redirect": "/.auth/login/aad?post_login_redirect_uri=.referrer", "statusCode": 302 - } + }, + "403": { + "rewrite": "/403.html" + }The
routesarray is unchanged:*and/api/*still requireadmin,/logoutstill redirects to/.auth/logoutwith no role,/loginstill rewrites to/.auth/login/aad, and/.auth/login/githubstill answers 404. The 401 override is byte-for-byte the same.navigationFallbackis unchanged. Arewriteoverride keeps the 403 status and only replaces the body. NostatusCodeis set on it, so the status is not turned into 200.Who gets what, before and after:
/,/games)/.auth/login/aad?post_login_redirect_uri=<current page>; after sign-in the user is back on that pageadmin, page navigation/403.html: "You are signed in, but this account is not allowed to use Event Manager", plus a link to/logoutadmin,/api/*/403.htmlbody. No data either wayWhy 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-inGET /.auth/meon 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 theadminrole. 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/meprobe 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 directGET /403.htmlstill falls under*and needsadmin, like every other file.Change
MW-GC.EventManager.Web/Services/SessionExpiredHandler.cs(new): theDelegatingHandlerdescribed above. It handles only requests whose path starts with/api/.MW-GC.EventManager.Web/Program.cs: the scopedHttpClientis built onSessionExpiredHandler→HttpClientHandler.BaseAddressand the 30 secondTimeoutare 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 recordingNavigationManager.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/andobj/deleted first).d5e5476(card tip)d5e5476d24ab2e(final head)dev moved from
d5e5476tod24ab2e(#84) during the work. #84 touchesCONTEXT.md,Events.razorandEditEventSnapshotTests.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):UnauthorizedOnAnApiCallSendsTheUserToSignInOnceSignInReturnsToTheCurrentPathAndQueryApiCallThatFollowedARedirectToTheSignInRouteSendsTheUserToSignInApiCallAnsweredWithTheSignInPageAsHtmlSendsTheUserToSignInOpaqueFailureWhileSignedOutSendsTheUserToSignInAndRethrowsOpaqueFailureWhenTheSignInCheckAlsoFailsIsAnOutageAndDoesNotNavigateOpaqueFailureWhenTheSignInCheckAnswersAnErrorStatusDoesNotNavigateOpaqueFailureWhileStillSignedInDoesNotNavigateOpaqueFailureWhenTheSignInCheckIsNotJsonDoesNotNavigateTimeoutIsNotTreatedAsASignOutNonApiRequestIsPassedThroughUntouchedNonApiTransportFailureIsNotProbedTwoFailingCallsNavigateOnlyOnceOpaqueFailureAfterTheNavigationIsNotProbedAgainOtherApiFailureStatusIsPassedThroughUntouched(404, 500, 403, 400)SuccessfulApiJsonIsPassedThroughUntouchedRunning stack (
with-stack.sh: Azurite + API + Web + SWA CLI 2.0.10 onhttp://127.0.0.1:4280, Release web build behind SWA), on the final heada62b445:api_flows.py: 10/10 passed.GET /api/gamesLocation: /.auth/login/aad?post_login_redirect_uri=%2Fapi%2Fgames,Content-Length: 0(the response the client must handle)Content-Type: text/html, the emulator's sign-in page (the case #73 and the handler'stext/htmlcheck cover)GET /.auth/me{"clientPrincipal":null}(what the outage probe looks for)GET /logoutLocation: http://127.0.0.1:4280/.auth/logoutGET /Location: /.auth/login/aad?post_login_redirect_uri=%2F(401 override unchanged)GET /.auth/meanonymous, authenticatedGET /,GET /games,GET /api/gamesGET /logoutLocation: http://127.0.0.1:4280/.auth/logout(reachable withoutadmin)GET /api/gamesapplication/json; charset=utf-8, game list (unchanged)GET /,GET /gamesindex.html(unchanged)GET /403.html<a href="/logout">, no<script>, no external URLEmulator 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,isRouteRequiringUserRolesCheckreturnsfalseboth for "no cookie" and for "roles don't match", anddist/msha/middlewares/request.middleware.jsthen always callshandleErrorPage(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:responseOverridesengine, given this config, turns a 403 into status 403 with the body rewritten toswa://403.html, and still turns a 401 into a 302 to/.auth/login/aad?post_login_redirect_uri=%2Fgames;/logoutis reachable for a non-admin.CI check-runs on the final head
a62b445(read back after the push):build-and-testsuccess,CodeQLsuccess,Analyze (actions)success,Analyze (csharp)success,Analyze (javascript-typescript)success,submit-nugetsuccess (6/6).Not run:
Notes
Closes #51takes effect whendevreachesmain. Nerd closes fix(web): send a signed-out user to sign in when an API call hits the SWA 401 redirect #51 by hand and sets the milestone.staticwebapp.config.json). This PR is outside the agent self-merge grant.