TOTP-based Multi-Factor Authentication support (Frontend) - #6107
Open
tomascohen wants to merge 3 commits into
Open
TOTP-based Multi-Factor Authentication support (Frontend)#6107tomascohen wants to merge 3 commits into
tomascohen wants to merge 3 commits into
Conversation
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
11 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
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 loginmfa.service.tswrapping all REST calls to/api/authn/mfa/*(status, setup, verify-setup, verify, disable, recovery-codes)LogInMfaComponentshown when JWT containsmfa_verified=false; supports both 6-digit TOTP code input and recovery code toggleauth.effects.tsintercepts successful authentication, decodes the JWT, and dispatchesMfaRequiredActionwhenmfa_verifiedis falseProfilePageMfaFormComponentfor enrollment (QR code rendering viaqrcodenpm package), disabling MFA (requires current TOTP code), and regenerating recovery codesen.json5andde.json5qrcode^1.5.4 (MIT) and@types/qrcode^1.5.6 for client-side QR code generation.npmrc-- Addedlegacy-peer-deps=true(required due to existing peer dependency conflicts with mirador/react)How to test:
mfabranch fromthekesolutions/DSpace)Checklist
mainbranch of code.npm run lint.npm run check-circ-deps).qrcodeis MIT licensed.)