Skip to content

TOTP-based Multi-Factor Authentication support (Frontend) - #6107

Open
tomascohen wants to merge 3 commits into
DSpace:mainfrom
thekesolutions:mfa
Open

TOTP-based Multi-Factor Authentication support (Frontend)#6107
tomascohen wants to merge 3 commits into
DSpace:mainfrom
thekesolutions:mfa

Conversation

@tomascohen

Copy link
Copy Markdown

References

Description

Adds the frontend components for TOTP-based Multi-Factor Authentication: a two-step login flow with TOTP/recovery code verification, and a profile page form for MFA enrollment, disabling, and recovery code management.

Instructions for Reviewers

List of changes in this PR:

  • NgRx state management -- New actions (MFA_REQUIRED, MFA_VERIFY, MFA_VERIFY_SUCCESS, MFA_VERIFY_ERROR, MFA_RESET), effects, and auth reducer/selector extensions to handle the MFA verification state during login
  • MFA HTTP service -- mfa.service.ts wrapping all REST calls to /api/authn/mfa/* (status, setup, verify-setup, verify, disable, recovery-codes)
  • Two-step login flow -- LogInMfaComponent shown when JWT contains mfa_verified=false; supports both 6-digit TOTP code input and recovery code toggle
  • JWT payload parsing -- auth.effects.ts intercepts successful authentication, decodes the JWT, and dispatches MfaRequiredAction when mfa_verified is false
  • Profile page MFA form -- ProfilePageMfaFormComponent for enrollment (QR code rendering via qrcode npm package), disabling MFA (requires current TOTP code), and regenerating recovery codes
  • i18n keys -- Added MFA-related translation keys to en.json5 and de.json5
  • New dependencies -- qrcode ^1.5.4 (MIT) and @types/qrcode ^1.5.6 for client-side QR code generation
  • .npmrc -- Added legacy-peer-deps=true (required due to existing peer dependency conflicts with mirador/react)

How to test:

  1. Start DSpace backend with the MFA PR applied (or use the mfa branch from thekesolutions/DSpace)
  2. Start this Angular frontend
  3. Log in with a user that does NOT have MFA enabled -- login works normally
  4. Go to Profile page -- you should see "Multi-Factor Authentication" section with a "Set up" button
  5. Click "Set up" -- a QR code is displayed. Scan it with any authenticator app
  6. Enter the 6-digit code and confirm -- recovery codes are displayed. Save them
  7. Log out and log back in -- after entering password, a second step appears asking for the TOTP code
  8. Enter the code from your authenticator app -- login completes
  9. Test recovery code: on the TOTP step, click "Use a recovery code" and enter one of the saved codes
  10. Test disable: go to Profile, click "Disable MFA", enter current TOTP code to confirm

Checklist

  • My PR is created against the main branch of code.
  • My PR is small in size (e.g. less than 1,000 lines of code). Note: ~1,714 lines across 29 files. This is a complete feature covering state management, login flow, and profile UI. Splitting would make review harder.
  • My PR follows all coding best practices based on the Code Conventions Guide.
  • My PR passes ESLint validation using npm run lint.
  • My PR doesn't introduce circular dependencies (verified via npm run check-circ-deps).
  • My PR includes TypeDoc comments for all new public methods and classes.
  • My PR passes all specs/tests and includes new/updated specs or tests.
  • My PR aligns with Accessibility guidelines (form labels, ARIA attributes, keyboard navigation for code input).
  • My PR uses i18n (internationalization) keys instead of hardcoded English text.
  • My PR includes details on how to test it.
  • If my PR includes new libraries/dependencies, I've made sure their licenses align with the DSpace BSD License. (qrcode is MIT licensed.)
  • If my PR includes new features or configurations, I've provided basic technical documentation in the PR itself.
  • If my PR fixes an issue ticket, I've linked them together.

Companion to DSpace/DSpace#12703 (backend MFA implementation).

This patch adds the core state management infrastructure for the
two-step MFA login flow in the Angular frontend.

Architecture decisions:

1. NgRx for MFA state (not component-local state):
   The MFA flow spans multiple components (login form -> MFA input)
   and requires coordination with the existing auth effects pipeline.
   NgRx ensures the MFA-pending token is preserved across component
   boundaries and the flow can be interrupted/resumed cleanly.

2. Separate mfa.actions.ts / mfa.effects.ts (not merged into auth.*):
   Keeps MFA logic isolated and removable. The auth.reducer.ts is
   extended with MFA fields since the state must be in the same slice
   for selector composition.

3. MfaService uses HttpClient directly (not DSpace HAL client):
   The MFA endpoints return plain JSON (not HAL+JSON), so the complex
   HAL parsing infrastructure is unnecessary. The service explicitly
   attaches the Bearer token from AuthService.getToken() since the
   global AuthInterceptor may not have the token available during the
   MFA-pending state.

4. JWT claim inspection in authenticateSuccess$:
   The effect decodes the JWT payload (base64) to check mfa_verified.
   This is safe because we only read a boolean - the signature is
   validated server-side. This avoids an extra round-trip to /status.

5. MFA verify uses observe: response to capture Authorization header:
   After successful TOTP verification, the backend issues a new JWT
   in the response Authorization header. The effect extracts it and
   dispatches AuthenticationSuccessAction to continue normal login.

State shape additions to AuthState:
  mfaRequired: boolean     - true when TOTP input should be shown
  mfaPendingToken: AuthTokenInfo - the mfa_verified=false token
  mfaError: string         - verification error message
  mfaVerifying: boolean    - loading state during verify call

New selectors: isMfaRequired, isMfaVerifying, getMfaError,
getMfaPendingToken

Test plan:
1. Apply patch
2. Build: npm run build
=> SUCCESS: No compilation errors
3. Sign off :-D
This patch modifies the login page to support MFA verification as a
second step after successful password authentication.

UX flow:
  1. User enters email + password -> AuthenticateAction
  2. Backend returns JWT with mfa_verified=false
  3. authenticateSuccess$ detects claim -> MfaRequiredAction
  4. Login form hides, LogInMfaComponent appears
  5. User enters 6-digit TOTP code (or recovery code)
  6. MfaVerifyAction -> POST /api/authn/mfa/verify with pending token
  7. Backend returns new JWT with mfa_verified=true in response header
  8. AuthenticationSuccessAction dispatched -> normal auth flow resumes

Design decisions:

1. MFA step shown WITHIN the login page (not a separate route):
   Prevents URL-based state leakage and keeps the flow atomic.
   If the user navigates away, the MFA state resets (MfaResetAction).

2. LogInMfaComponent is standalone (not a login "method"):
   MFA is not an authentication METHOD (like Shibboleth/OIDC) - it is
   a second FACTOR within the password method. It renders conditionally
   based on mfaRequired selector, replacing the method list.

3. Pending token passed explicitly in Authorization header:
   During the MFA step, the token is NOT stored in the auth cookie
   (because the normal auth flow was intercepted). The verify effect
   reads mfaPendingToken from the store and passes it directly.

4. Recovery code toggle:
   Same input field with relaxed validation (any string vs 6-digit
   pattern). Dispatches MfaVerifyAction with recoveryCode field.

5. Uses dsBtnDisabled directive (DSpace convention):
   Buttons use [dsBtnDisabled] instead of [disabled] per project lint
   rules, ensuring consistent accessible disabled-state styling.

6. Custom theme compatibility:
   The custom theme's LogInComponent imports are updated to include
   LogInMfaComponent since it inherits the base template.

Test plan:
1. Apply patch (requires running backend with MFA-enrolled user)
2. Navigate to /login, submit valid credentials
=> SUCCESS: TOTP code input appears
3. Enter valid 6-digit code from authenticator app
=> SUCCESS: Login completes, redirected to homepage
4. Click "Use a recovery code instead", enter recovery code
=> SUCCESS: Login completes
5. Click "Cancel"
=> SUCCESS: Returns to password form
6. Sign off :-D
This patch adds a "Two-Factor Authentication" card to the user profile
page, providing the complete MFA lifecycle management UI, and adds
client-side QR code generation.

QR code rendering - qrcode library (v1.5.4, MIT license):
The QR code for the TOTP provisioning URI is generated entirely
client-side using a <canvas> element. No external services (Google
Charts API, QR Server, etc.) are involved. This is a deliberate
decision: academic tools aimed at digital preservation must not depend
on third-party services subject to arbitrary policy changes,
deprecation, or rate limits. The qrcode library is pure JavaScript
with zero runtime dependencies.

Profile page MFA card features:
- Setup mode: generates secret via POST /mfa/setup, renders QR code
  from the otpauth:// provisioning URI on a canvas element
- Enrollment confirmation: validates first TOTP code, displays
  recovery codes (shown once, never stored in plaintext client-side)
- Status display: shows enabled badge + remaining recovery code count
- Disable: requires current TOTP code (prevents unauthorized disable)
- Regenerate recovery codes: requires current TOTP code

Design decisions:

1. QR rendered in ngAfterViewChecked (not ngOnInit):
   The canvas element is inside an @if block. It only exists in the
   DOM after provisioningUri$ emits. AfterViewChecked ensures the
   canvas is available when we call QRCode.toCanvas().

2. BehaviorSubjects (not NgRx) for profile component state:
   The profile MFA card is self-contained and does not need cross-
   component coordination. Local reactive state with BehaviorSubjects
   keeps it simple and testable without NgRx boilerplate.

3. All destructive operations require TOTP code:
   Disable and regenerate-codes both require a valid current code.
   This prevents a session-hijacker from removing MFA protection.

4. Custom theme compatibility:
   ProfilePageMfaFormComponent added to custom theme's imports array.

New dependencies:
- qrcode@1.5.4 (MIT) - client-side QR generation
- @types/qrcode (devDep) - TypeScript type definitions

i18n keys added: login.mfa.*, profile.mfa.* (25 keys total)

Test plan:
1. Apply patch
2. Login, navigate to /profile
=> SUCCESS: "Two-Factor Authentication" card visible
3. Click setup, verify QR code renders (no network requests to external)
4. Scan with authenticator app, enter code
=> SUCCESS: Recovery codes displayed
5. Run: npm run lint
=> SUCCESS: 0 errors
6. Sign off :-D
@lgeggleston lgeggleston changed the title MFA TOTP-based Multi-Factor Authentication support (Frontend) Aug 19, 2026
@lgeggleston lgeggleston added authentication: general general authentication issues new feature labels Aug 19, 2026
@lgeggleston lgeggleston moved this to 🙋 Needs Reviewers Assigned in DSpace 11.0 Release Aug 19, 2026
@tdonohue
tdonohue requested a review from steph-ieffam August 20, 2026 14:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

authentication: general general authentication issues new feature

Projects

Status: 🙋 Needs Reviewers Assigned

Development

Successfully merging this pull request may close these issues.

Add TOTP-based Multi-Factor Authentication UI

2 participants