Skip to content

Repository files navigation

🔐 Django REST Auth JWT

Professional Authentication System for Django REST Framework

Django DRF Python JWT License

GitHub Stars GitHub Forks

English | فارسی


📖 About

A production-ready, fully-documented authentication system for Django REST Framework that implements JWT-based authentication with email verification. This project is designed to help developers understand and implement a complete authentication flow without relying on third-party authentication packages.

🌟 Why This Project?

Many backend developers struggle with implementing authentication in Django REST Framework. This project serves as:

  • 📚 Educational Resource: Learn authentication best practices
  • 🚀 Production Template: Start your project with solid authentication
  • 🔧 Customizable Foundation: Easy to extend and modify for your needs
  • 📖 Well-Documented: Every component is thoroughly documented

✨ Features

🔑 Authentication & Authorization

  • Email-based Authentication - No username required
  • JWT Token Management - Secure token-based auth
  • Token Refresh & Blacklist - Secure token rotation
  • Email Verification - Verify user emails with JWT tokens

🔒 Password Management

  • Password Change - Secure password updates for authenticated users
  • Password Reset - Email-based password recovery
  • Strong Password Validation - Built-in password strength requirements

👤 User Management

  • Custom User Model - Email as primary identifier
  • User Profile - Retrieve and manage user information
  • Admin Interface - Enhanced Django admin for user management

📝 Documentation

  • Swagger UI - Interactive API documentation
  • ReDoc - Beautiful API documentation
  • Type Hints - Full Python type annotations
  • Comprehensive Comments - Well-commented codebase

🐳 DevOps Ready

  • Docker Support - Containerized deployment
  • Docker Compose - One-command development setup
  • Environment Variables - Secure configuration management
  • Production Ready - Optimized settings for deployment

🚀 Quick Start

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)
  • Git

Installation

1️⃣ Clone the repository

git clone https://github.com/mobin-gpr/django-rest-auth-jwt.git
cd django-rest-auth-jwt

2️⃣ Create and activate virtual environment

# Create virtual environment
python -m venv venv

# Activate on Windows
venv\Scripts\activate

# Activate on macOS/Linux
source venv/bin/activate

3️⃣ Install dependencies

pip install -r requirements.txt

4️⃣ Set up environment variables

# Copy the example environment file
cp .env.example .env

# Generate a secret key
python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'

# Edit .env and add the generated secret key

5️⃣ Run migrations

python manage.py migrate

6️⃣ Create superuser (optional)

python manage.py createsuperuser

7️⃣ Run the development server

python manage.py runserver

🎉 Done! Visit http://localhost:8000/api/docs/swagger/ to see the API documentation.


🐳 Docker Quick Start

For a faster setup using Docker:

# Build and start containers
docker-compose up --build

# Run migrations
docker-compose exec web python manage.py migrate

# Create superuser
docker-compose exec web python manage.py createsuperuser

📚 API Endpoints

🔐 Authentication

Method Endpoint Description Auth Required
POST /api/v1/accounts/register/ Register a new user
GET /api/v1/accounts/confirm_email/<token>/ Verify email address
POST /api/v1/accounts/resend_confirm_email/ Resend verification email
POST /api/v1/accounts/jwt/token/ Obtain JWT token (login)
POST /api/v1/accounts/jwt/token/refresh/ Refresh access token
POST /api/v1/accounts/jwt/token/verify/ Verify token validity
POST /api/v1/accounts/jwt/token/blacklist/ Blacklist refresh token (logout)

🔑 Password Management

Method Endpoint Description Auth Required
PUT /api/v1/accounts/change_password/ Change password
POST /api/v1/accounts/reset_password/ Request password reset
POST /api/v1/accounts/set_password/<token>/ Set new password after reset

👤 User Profile

Method Endpoint Description Auth Required
GET /api/v1/accounts/profile/ Get user profile

📖 Documentation

Endpoint Description
/api/docs/swagger/ Swagger UI documentation
/api/docs/redoc/ ReDoc documentation
/admin/ Django admin interface

🔧 Configuration

Environment Variables

Create a .env file in the project root (use .env.example as template):

# Security
SECRET_KEY=your-secret-key-here
DEBUG=False
ALLOWED_HOSTS=localhost,127.0.0.1

# JWT Configuration
ACCESS_TOKEN_LIFETIME_MINUTES=60
REFRESH_TOKEN_LIFETIME_DAYS=7

# Email Configuration
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-app-password

📖 Documentation

📘 API Documentation

  • Swagger UI: Visit /api/docs/swagger/ for interactive API documentation
  • ReDoc: Visit /api/docs/redoc/ for beautiful, readable API docs

🔍 Key Implementation Details

Custom User Model

  • Email-based authentication (no username field)
  • Email verification status tracking
  • Enhanced admin interface

JWT Token System

  • Custom token generation with email in payload
  • Secure token decoding with error handling
  • Token refresh and blacklisting support

Email Verification

  • Asynchronous email sending using threading
  • JWT tokens for verification (not stored in database)
  • Configurable token expiration

Password Security

  • Django's built-in password validators
  • Minimum 8 characters requirement
  • Password strength validation

🏗️ Project Structure

django-rest-auth-jwt/
├── accounts/               # User authentication app
│   ├── migrations/         # Database migrations
│   ├── admin.py           # Admin configuration
│   ├── models.py          # Custom User model
│   ├── serializers.py     # API serializers
│   ├── urls.py            # App URL patterns
│   └── views.py           # API views
├── config/                # Project configuration
│   ├── settings.py        # Django settings
│   ├── urls.py            # Main URL configuration
│   └── wsgi.py            # WSGI configuration
├── utils/                 # Utility modules
│   ├── email.py           # Email utilities
│   └── jwt_token.py       # JWT token utilities
├── .env.example           # Environment variables template
├── .gitignore            # Git ignore file
├── docker-compose.yml    # Docker Compose configuration
├── Dockerfile            # Docker configuration
├── manage.py             # Django management script
├── README.md             # This file
└── requirements.txt      # Python dependencies

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

See CONTRIBUTING.md for detailed guidelines.


📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


👨‍💻 Author

Mobin Ghanbarpour


🙏 Acknowledgments

  • Django team for the amazing framework
  • Django REST Framework team for the powerful toolkit
  • Simple JWT team for the authentication library
  • All contributors who help improve this project

⭐ Show Your Support

If this project helped you, please give it a ⭐️! It helps others discover it too.


📮 Contact

Have questions or suggestions? Feel free to:


⬆ Back to Top

Made with ❤️ by Mobin Ghanbarpour

About

This project offers a custom-built authentication system for Django REST Framework, without relying on third-party packages. It includes email account verification and JWT-based login, designed as a resource for developers

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

7 stars

Watchers

1 watching

Forks

Used by

Contributors

Languages