Skip to content

Nadiar/flask-2fa-secure-app

Repository files navigation

Secure Flask App with 2FA

A secure Flask web application featuring two-factor authentication (2FA), comprehensive security measures, and best practices for authentication.

Features

Security Features

  • Two-Factor Authentication (2FA) using TOTP (Time-based One-Time Password)
  • Secure Password Hashing with PBKDF2-SHA256
  • Account Lockout Protection after multiple failed login attempts
  • CSRF Protection on all forms
  • Security Headers (X-Frame-Options, CSP, HSTS, etc.)
  • Session Security with HttpOnly, Secure, and SameSite cookies
  • Login Attempt Auditing for security monitoring
  • Backup Codes for 2FA recovery

User Features

  • User registration with strong password requirements
  • Secure login with optional "Remember Me"
  • Dashboard with account information
  • Easy 2FA setup with QR code
  • Backup codes for account recovery

Installation

  1. Clone the repository:
cd flask-2fa-secure-app
  1. Create a virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install the package:
pip install -e .
  1. Install development dependencies:
pip install -e ".[dev]"
  1. Set up environment variables:
cp .env.example .env
# Edit .env and set a secure SECRET_KEY

Running the Application

Development Mode

python -m flask --app src.flask_2fa_secure_app.app run

Or:

python src/flask_2fa_secure_app/app.py

The application will be available at http://127.0.0.1:5000

Production Deployment

For production, use a WSGI server like Gunicorn:

pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 'src.flask_2fa_secure_app.app:create_app()'

Important: Ensure you set proper environment variables in production:

  • SECRET_KEY - A strong, random secret key
  • SESSION_COOKIE_SECURE=True - Only send cookies over HTTPS
  • FLASK_ENV=production

Usage

  1. Register a new account:

    • Navigate to /register
    • Create an account with a strong password (min 8 chars, uppercase, lowercase, number, special character)
  2. Login:

    • Navigate to /login
    • Enter your credentials
  3. Enable 2FA:

    • After logging in, go to the Dashboard
    • Click "Enable 2FA"
    • Scan the QR code with an authenticator app (Google Authenticator, Microsoft Authenticator, Authy)
    • Enter the verification code
    • Save the backup codes in a secure location
  4. Login with 2FA:

    • After enabling 2FA, you'll be prompted for a code after entering your password
    • Enter the 6-digit code from your authenticator app

Security Measures

Password Security

  • Passwords are hashed using PBKDF2-SHA256
  • Minimum length and complexity requirements enforced
  • No password storage in plain text

Account Protection

  • Account locked for 15 minutes after 5 failed login attempts
  • Failed login attempts tracked per user
  • Login attempts logged for security auditing

Session Security

  • Sessions expire after 30 minutes of inactivity
  • HttpOnly cookies prevent XSS attacks
  • Secure flag ensures cookies only sent over HTTPS (in production)
  • SameSite=Strict prevents CSRF attacks

Two-Factor Authentication

  • TOTP implementation with 30-second time window
  • QR code generation for easy setup
  • Backup codes for account recovery
  • Each backup code can only be used once

Security Headers

  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=31536000
  • Content Security Policy configured

Testing

Run the test suite:

pytest

Run security tests:

bandit -r src/
safety check

Run E2E tests with Playwright:

playwright install
pytest tests/e2e/

Project Structure

flask-2fa-secure-app/
├── src/
│   └── flask_2fa_secure_app/
│       ├── __init__.py
│       ├── app.py              # Main application
│       ├── models.py            # Database models
│       ├── forms.py             # WTForms
│       └── templates/           # HTML templates
│           ├── base.html
│           ├── index.html
│           ├── login.html
│           ├── register.html
│           ├── two_factor.html
│           ├── dashboard.html
│           ├── setup_2fa.html
│           └── backup_codes.html
├── tests/                       # Test suite
├── pyproject.toml              # Project configuration
├── .env.example                # Environment variables template
└── README.md

Security Considerations

For Production Deployment

  1. Always use HTTPS - Set SESSION_COOKIE_SECURE=True
  2. Use a strong SECRET_KEY - Generate with python -c "import os; print(os.urandom(32).hex())"
  3. Enable rate limiting - Consider using Flask-Limiter
  4. Monitor login attempts - Review the login_attempts table regularly
  5. Keep dependencies updated - Run safety check regularly
  6. Use a production database - SQLite is for development only
  7. Set up proper logging - Monitor security events
  8. Configure firewall rules - Restrict access to the application

Known Limitations

  • This is a demonstration application
  • Additional security measures may be needed for high-security applications
  • Consider adding:
    • Rate limiting on all endpoints
    • Email verification
    • Password reset functionality
    • IP-based blocking
    • Advanced threat detection

License

MIT License - See LICENSE file for details

Contributing

Contributions are welcome! Please ensure all security tests pass before submitting PRs.

About

Production-ready Flask web application with secure 2FA authentication using TOTP and backup codes

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •