[PR #22206] feat: implement Multi-Factor Authentication (MFA) with TOTP and backup codes #29862

Closed
opened 2026-02-21 20:46:23 -05:00 by yindo · 0 comments
Owner

Original Pull Request: https://github.com/langgenius/dify/pull/22206

State: closed
Merged: No


Multi-Factor Authentication (MFA) Implementation

Important

  1. Make sure you have read our contribution guidelines
  2. Ensure there is an associated issue and you have been assigned to it
  3. Use the correct syntax to link this PR: Fixes #<issue number>.

Summary

This PR implements a comprehensive Multi-Factor Authentication (MFA) system for Dify using TOTP (Time-based One-Time Password) and backup codes. This enhancement significantly improves account security by requiring a second factor of authentication beyond just passwords.

Features Implemented

  • TOTP Authentication: RFC 6238 compliant integration with authenticator apps (Google Authenticator, Authy, etc.)
  • Backup Codes: 10 single-use backup codes for account recovery
  • Account Integration: MFA settings accessible from Account page with intuitive UI
  • Secure Implementation: Encrypted secret storage, proper session handling
  • Internationalization: Support for multiple languages (English, Japanese, German, Chinese)

⚠️ Migration Required

This implementation requires a database migration to add MFA functionality:

# Run database migration
flask db upgrade

# Or using Docker
docker exec dify-api flask db upgrade

Migration Details:

  • File: api/migrations/versions/2025_07_08_1500-abc123def456_add_account_mfa_settings_table.py
  • Changes: Adds account_mfa_settings table for storing MFA data
  • Schema: Includes fields for account_id, enabled, secret, backup_codes, setup_at

Database Schema Changes

CREATE TABLE account_mfa_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID NOT NULL REFERENCES accounts(id),
    enabled BOOLEAN DEFAULT FALSE,
    secret VARCHAR(255),
    backup_codes TEXT, -- JSON array of backup codes
    setup_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Technical Implementation

Backend (API)

  • New Endpoints: /console/api/account/mfa/* for MFA management
  • MFA Service: Complete business logic for TOTP and backup codes
  • Security: Encrypted secret storage and secure verification processes
  • Error Handling: Comprehensive error responses and validation

Frontend (Web)

  • MFA Setup Flow: QR code generation and TOTP verification
  • Account Page Integration: Clean UI for MFA management
  • Login Flow: Seamless MFA verification during authentication
  • Modal Components: User-friendly setup and disable workflows
  • Error Handling: Comprehensive error states and user feedback

Security Considerations

  • TOTP secrets are encrypted before database storage
  • Backup codes are hashed and single-use only
  • Proper session validation for all MFA operations
  • Password verification required for MFA disable
  • Rate limiting applied to MFA verification attempts
  • RFC 6238 compliance for TOTP implementation

Files Changed

Core Implementation (18 files)

  • MFA.md - Complete MFA specification and documentation
  • api/controllers/console/auth/mfa.py - MFA API endpoints
  • api/services/mfa_service.py - MFA business logic
  • api/migrations/versions/*_add_account_mfa_settings_table.py - Database migration
  • web/app/components/header/account-setting/mfa-page.tsx - MFA UI component
  • web/app/signin/components/mfa-verification.tsx - Login MFA verification
  • web/service/use-mfa.ts - Frontend MFA service
  • web/i18n/*/mfa.ts - Internationalization files
  • And 10 other core files for integration

Testing & Development

  • web/app/components/header/account-setting/mfa-page.spec.tsx - Frontend unit tests
  • api/tests/unit_tests/controllers/console/auth/test_mfa.py - Backend unit tests
  • docker/Dockerfile.web.dev - Development environment improvements
  • web/jest.config.ts - Enhanced Jest configuration
  • Test mocks and utilities

Documentation

  • docs/MFA_IMPLEMENTATION.md - Implementation guide
  • docs/MFA_TESTING.md - Testing documentation

Screenshots

Before After
Basic password-only authentication Two-factor authentication with TOTP support
No MFA settings in Account page Comprehensive MFA management interface
Single-factor login flow Enhanced login with MFA verification step

Testing

Manual Testing

  • All MFA functionality tested and working correctly in browser
  • Setup Flow: QR code → authenticator app → verification
  • Login Flow: Password → MFA prompt → TOTP/backup code
  • Disable Flow: Password confirmation → MFA disabled
  • Error Handling: Invalid codes, expired tokens, network errors

Unit Testing ⚠️

  • Comprehensive unit tests implemented for both frontend and backend
  • Frontend test execution environment has technical challenges
  • Jest/Next.js integration issues cause extended execution times (90+ seconds)
  • Tests are well-written but environment requires optimization
  • Backend tests cover all MFA service methods and API endpoints

Known Issues

  • Frontend unit test execution environment needs optimization
  • Test execution time is currently suboptimal
  • These issues don't affect the actual MFA functionality

Future Enhancements

  • Backup code regeneration functionality
  • Device remember feature ("Don't ask on this device for 30 days")
  • Admin controls for MFA enforcement policies
  • Audit logging for MFA-related security events
  • SMS-based MFA as alternative option
  • Hardware token support (U2F/WebAuthn)

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran dev/reformat(backend) and cd web && npx lint-staged(frontend) to appease the lint gods

*This implementation provides a solid foundation for multi-factor authentication while maintaining security best practices and following Dify's existing architectural patterns.\

**Original Pull Request:** https://github.com/langgenius/dify/pull/22206 **State:** closed **Merged:** No --- # Multi-Factor Authentication (MFA) Implementation > [!IMPORTANT] > > 1. Make sure you have read our [contribution guidelines](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md) > 2. Ensure there is an associated issue and you have been assigned to it > 3. Use the correct syntax to link this PR: `Fixes #<issue number>`. ## Summary This PR implements a comprehensive Multi-Factor Authentication (MFA) system for Dify using TOTP (Time-based One-Time Password) and backup codes. This enhancement significantly improves account security by requiring a second factor of authentication beyond just passwords. ### Features Implemented - **TOTP Authentication**: RFC 6238 compliant integration with authenticator apps (Google Authenticator, Authy, etc.) - **Backup Codes**: 10 single-use backup codes for account recovery - **Account Integration**: MFA settings accessible from Account page with intuitive UI - **Secure Implementation**: Encrypted secret storage, proper session handling - **Internationalization**: Support for multiple languages (English, Japanese, German, Chinese) ## ⚠️ Migration Required This implementation requires a database migration to add MFA functionality: ```bash # Run database migration flask db upgrade # Or using Docker docker exec dify-api flask db upgrade ``` **Migration Details:** - **File**: `api/migrations/versions/2025_07_08_1500-abc123def456_add_account_mfa_settings_table.py` - **Changes**: Adds `account_mfa_settings` table for storing MFA data - **Schema**: Includes fields for `account_id`, `enabled`, `secret`, `backup_codes`, `setup_at` ### Database Schema Changes ```sql CREATE TABLE account_mfa_settings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), account_id UUID NOT NULL REFERENCES accounts(id), enabled BOOLEAN DEFAULT FALSE, secret VARCHAR(255), backup_codes TEXT, -- JSON array of backup codes setup_at TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` ### Technical Implementation #### Backend (API) - **New Endpoints**: `/console/api/account/mfa/*` for MFA management - **MFA Service**: Complete business logic for TOTP and backup codes - **Security**: Encrypted secret storage and secure verification processes - **Error Handling**: Comprehensive error responses and validation #### Frontend (Web) - **MFA Setup Flow**: QR code generation and TOTP verification - **Account Page Integration**: Clean UI for MFA management - **Login Flow**: Seamless MFA verification during authentication - **Modal Components**: User-friendly setup and disable workflows - **Error Handling**: Comprehensive error states and user feedback ### Security Considerations - TOTP secrets are encrypted before database storage - Backup codes are hashed and single-use only - Proper session validation for all MFA operations - Password verification required for MFA disable - Rate limiting applied to MFA verification attempts - RFC 6238 compliance for TOTP implementation ### Files Changed #### Core Implementation (18 files) - `MFA.md` - Complete MFA specification and documentation - `api/controllers/console/auth/mfa.py` - MFA API endpoints - `api/services/mfa_service.py` - MFA business logic - `api/migrations/versions/*_add_account_mfa_settings_table.py` - Database migration - `web/app/components/header/account-setting/mfa-page.tsx` - MFA UI component - `web/app/signin/components/mfa-verification.tsx` - Login MFA verification - `web/service/use-mfa.ts` - Frontend MFA service - `web/i18n/*/mfa.ts` - Internationalization files - And 10 other core files for integration #### Testing & Development - `web/app/components/header/account-setting/mfa-page.spec.tsx` - Frontend unit tests - `api/tests/unit_tests/controllers/console/auth/test_mfa.py` - Backend unit tests - `docker/Dockerfile.web.dev` - Development environment improvements - `web/jest.config.ts` - Enhanced Jest configuration - Test mocks and utilities #### Documentation - `docs/MFA_IMPLEMENTATION.md` - Implementation guide - `docs/MFA_TESTING.md` - Testing documentation ## Screenshots | Before | After | |--------|-------| | Basic password-only authentication | Two-factor authentication with TOTP support | | No MFA settings in Account page | Comprehensive MFA management interface | | Single-factor login flow | Enhanced login with MFA verification step | ## Testing ### Manual Testing ✅ - All MFA functionality tested and working correctly in browser - **Setup Flow**: QR code → authenticator app → verification ✅ - **Login Flow**: Password → MFA prompt → TOTP/backup code ✅ - **Disable Flow**: Password confirmation → MFA disabled ✅ - **Error Handling**: Invalid codes, expired tokens, network errors ✅ ### Unit Testing ⚠️ - Comprehensive unit tests implemented for both frontend and backend - Frontend test execution environment has technical challenges - Jest/Next.js integration issues cause extended execution times (90+ seconds) - Tests are well-written but environment requires optimization - Backend tests cover all MFA service methods and API endpoints ### Known Issues - Frontend unit test execution environment needs optimization - Test execution time is currently suboptimal - These issues don't affect the actual MFA functionality ## Future Enhancements - Backup code regeneration functionality - Device remember feature ("Don't ask on this device for 30 days") - Admin controls for MFA enforcement policies - Audit logging for MFA-related security events - SMS-based MFA as alternative option - Hardware token support (U2F/WebAuthn) ## Checklist - [ ] This change requires a documentation update, included: [Dify Document](https://github.com/langgenius/dify-docs) - [x] I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!) - [x] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change. - [x] I've updated the documentation accordingly. - [x] I ran `dev/reformat`(backend) and `cd web && npx lint-staged`(frontend) to appease the lint gods --- *This implementation provides a solid foundation for multi-factor authentication while maintaining security best practices and following Dify's existing architectural patterns.\
yindo added the pull-request label 2026-02-21 20:46:23 -05:00
yindo closed this issue 2026-02-21 20:46:23 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#29862