Skip to content

Sjekk token og redirect til innlogging når et kall gir 401 - #2435

Open
sonwit wants to merge 1 commit into
mainfrom
fix/3643-check-token-on-401
Open

Sjekk token og redirect til innlogging når et kall gir 401#2435
sonwit wants to merge 1 commit into
mainfrom
fix/3643-check-token-on-401

Conversation

@sonwit

@sonwit sonwit commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Når et API-kall svarer 401 (f.eks. brukeren har logget ut i en annen fane) sjekker vi nå tokenet via authentication/refresh før feilen sendes videre:

  • Refresh feiler → tokenet er utgått → redirect til innlogging.
  • Refresh lykkes → tokenet er gyldig, 401-en er en "ekte" feil og håndteres som før i komponenten

basert på eksempel fra RTK sin dokumentasjon her https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#automatic-re-authorization-by-extending-fetchbasequery

axios ble kun brukt i RefreshToken, så den er også fjernet.

Related Issue(s)

Altinn/altinn-authorization-tmp#3643

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features

    • Added centralized authentication handling for API requests.
    • Automatically refreshes expired sessions after authorization failures.
    • Redirects to the login page when session refresh is unsuccessful.
    • Prevents duplicate refresh requests when multiple requests expire simultaneously.
  • Bug Fixes

    • Improved consistency of authentication and security headers across API requests.
  • Tests

    • Added coverage for successful requests, session refreshes, failed refreshes, redirects, and concurrent authorization failures.

@github-actions github-actions Bot added bugfix kind/bug Used when something isn't working labels Aug 19, 2026
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cd3ffe50-0e2f-4af1-b1ce-8a06b0a52e04

📥 Commits

Reviewing files that changed from the base of the PR and between bb8baee and 66ef3a5.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (23)
  • package.json
  • src/resources/Token/RefreshToken.tsx
  • src/resources/Token/tokenUtils.ts
  • src/resources/utils/pathUtils.tsx
  • src/rtk/app/baseQuery.test.ts
  • src/rtk/app/baseQuery.ts
  • src/rtk/features/accessPackageApi.ts
  • src/rtk/features/altinnCdnApi.ts
  • src/rtk/features/clientApi.ts
  • src/rtk/features/connectionApi.ts
  • src/rtk/features/consentApi.ts
  • src/rtk/features/idPortenAuthorizationApi.ts
  • src/rtk/features/instanceApi.ts
  • src/rtk/features/lookupApi.ts
  • src/rtk/features/maskinportenApi.ts
  • src/rtk/features/requestApi.ts
  • src/rtk/features/resourceApi.ts
  • src/rtk/features/roleApi.ts
  • src/rtk/features/selfIdentifiedUserApi.ts
  • src/rtk/features/settingsApi.ts
  • src/rtk/features/singleRights/singleRightsApi.ts
  • src/rtk/features/systemUserApi.ts
  • src/rtk/features/userInfoApi.ts
💤 Files with no reviewable changes (1)
  • package.json

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The PR centralizes token refresh and login URL handling, adds shared RTK Query base-query behavior for 401 responses, migrates feature APIs to the shared helper, adds tests, and removes the unused axios dependency.

Changes

Authentication request flow

Layer / File(s) Summary
Token refresh and login redirect
src/resources/Token/RefreshToken.tsx, src/resources/Token/tokenUtils.ts, src/resources/utils/pathUtils.tsx, package.json
Token refreshes use a shared utility. Concurrent refresh requests share one in-flight request. Invalid sessions redirect to an encoded login URL. axios is removed.
Shared RTK Query base query
src/rtk/app/baseQuery.ts, src/rtk/app/baseQuery.test.ts
createBaseQuery prepares JSON and XSRF headers, refreshes tokens after 401 responses, preserves the original result, and handles concurrent failures. Tests cover success, refresh, redirect, and concurrency behavior.
Feature API integration
src/rtk/features/*Api.ts, src/rtk/features/singleRights/singleRightsApi.ts
Feature APIs use createBaseQuery(baseUrl) instead of local fetchBaseQuery and cookie-based header configuration. Endpoint definitions remain unchanged.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: ⚪ Minimal · up to 66ef3

The change centralizes 401 handling and token refresh behavior across API calls; no actionable merge-blocking risk remains based on the available evidence.

Suggested reviewers: allinox

Sequence Diagram(s)

sequenceDiagram
  participant RTKQuery
  participant createBaseQuery
  participant refreshToken
  participant AuthenticationEndpoint
  participant Browser
  RTKQuery->>createBaseQuery: execute API request
  createBaseQuery-->>RTKQuery: return 401 result
  createBaseQuery->>refreshToken: refreshToken()
  refreshToken->>AuthenticationEndpoint: send refresh request
  AuthenticationEndpoint-->>refreshToken: return refresh response
  refreshToken->>Browser: redirect to login URL when invalid
  createBaseQuery-->>RTKQuery: return original request result
Loading

Poem

One query gathers every thread,
A token wakes when hope has fled.
Shared headers march in neat array,
Concurrent calls now share the way.
If sessions fade, login lights the path.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Tittelen beskriver hovedendringen: tokenkontroll og omdirigering til innlogging ved HTTP 401.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/3643-check-token-on-401

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sonwit
sonwit requested a review from allinox August 19, 2026 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix kind/bug Used when something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant