A toolkit for handling OAuth with Django Rest Framework
Project description
DRF OAuth Toolkit
drf-oauth-toolkit is a flexible and lightweight OAuth2 integration library for Django Rest Framework (DRF), designed to simplify the process of adding OAuth2 support to your DRF projects.
🚀 Features
- ✅ Plug-and-play OAuth2 integration for DRF
- ✅ Supports multiple OAuth providers (Google, Facebook, etc.)
- ✅ Built-in token management and CSRF protection
- ✅ Customizable and extensible service classes
📦 Installation
pip install drf-oauth-toolkit
Add drf_oauth_toolkit to your settings.py:
INSTALLED_APPS = [
...
"drf_oauth_toolkit",
]
📖 Usage
- Configure OAuth credentials in your Django settings:
OAUTH_CREDENTIALS = {
"host": "http://127.0.0.1:8000",
"encryption_key": "Xcub4xIr71H3VR_PxDQdXAT39H9lM9nE2A0GQBg38Xo=",
"google": {
"client_id": "your google client id",
"client_secret": "your google client secert",
"callback_url": "google-callback",
},
}
- Extend the base service class to integrate a provider:
from drf_oauth_toolkit.views.google_views import GoogleOAuthCallbackApi, GoogleOAuthRedirectApi
urlpatterns = [
...
path("oauth2/google/login", GoogleOAuthRedirectApi.as_view(), name="google-login"),
path("oauth2/google/callback", GoogleOAuthCallbackApi.as_view(), name="google-callback"), # sure the url name matches the one in the settings
]
🎯 Inspiration
In my experience, OAuth integration has become a standard requirement across modern software projects. Whether you're integrating with Google, Facebook, or other OAuth providers, there are already some outstanding libraries available for Django and Django Rest Framework, such as:
- django-oauth-toolkit – A full-featured OAuth2 provider for Django.
- social-auth-app-django – A powerful social authentication library supporting multiple providers.
- dj-rest-auth – A drop-in solution for user registration and social authentication.
However, the challenge I aim to solve with drf-oauth-toolkit is the ease of use and flexibility. Many existing solutions assume a rigid workflow for how you should handle tokens and user management, often leading to challenges when working with DRF or when the library doesn’t align with your token handling requirements.
✅ Key Problems Addressed:
- Complex Setup: Some libraries require extensive setup with limited flexibility.
- Token Management Assumptions: Many solutions assume how tokens should be stored and used, which may not fit every project.
- DRF Integration: Some packages aren't well-optimized for Django Rest Framework out of the box.
🌟 Solution and Design Philosophy
drf-oauth-toolkit aims to simplify the OAuth integration process while maintaining full control and flexibility over how tokens are stored, validated, and extended. The core design principle is customizability — you can override and extend methods according to your project’s needs.
Example: Overriding Token Storage Logic
If you simply want to store tokens after a successful OAuth flow, you should not need to do anything, but in case you have a custom user model you can use something like below example:
from django.contrib.auth import get_user_model
from drf_oauth_toolkit.models import OAuth2Token, ServiceChoices
from drf_oauth_toolkit.services.google import GoogleOAuthService
from drf_oauth_toolkit.views.base import OAuthCallbackApiBase
User = get_user_model()
class GoogleOAuthCallbackApi(OAuthCallbackApiBase):
oauth_service_class = GoogleOAuthService
session_state_key = "google_oauth_state"
user_info_email_field = "email"
user_info_first_name_field = "given_name"
user_info_last_name_field = "family_name"
def update_account(self, user, oauth_tokens):
"""
Update or create a user account with the given OAuth tokens.
"""
if user is None:
user_info = self.oauth_service_class().get_user_info(oauth_tokens=oauth_tokens)
user = self.create_user_from_oauth(user_info)
OAuth2Token.objects.update_or_create_token(
user=user, service_name=ServiceChoices.GOOGLE, oauth_tokens=oauth_tokens
)
def create_user_from_oauth(self, user_info):
"""
Create a new user based on the information retrieved from the OAuth service.
"""
email = user_info.get(self.user_info_email_field)
first_name = user_info.get(self.user_info_first_name_field, "")
last_name = user_info.get(self.user_info_last_name_field, "")
user, _ = User.objects.get_or_create(
email=email,
defaults={
"first_name": first_name,
"last_name": last_name,
"username": email.split("@")[0],
},
)
return user
🎯 Extending for Specialized Use Cases
You can easily extend the base service for different OAuth providers. For example, handling YouTube OAuth integration:
class YouTubeOAuthService(GoogleOAuthService):
API_URI_NAME = "youtube_callback"
SCOPES = [
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/userinfo.email",
]
def fetch_channel_info(self, oauth_tokens: OAuthTokens) -> Dict[str, Any]:
self._ensure_valid_token(oauth_tokens)
headers = {"Authorization": f"Bearer {oauth_tokens.access_token}"}
response = requests.get(
"https://www.googleapis.com/youtube/v3/channels",
headers=headers,
params={"part": "snippet,contentDetails,statistics", "mine": "true"},
)
response.raise_for_status()
return response.json()
🎯 Next Steps and Enhancements
- Improved Documentation: Adding more inline code documentation and examples for clarity.
- Expanded Provider Support: Adding support for additional OAuth providers like Facebook and Microsoft.
- Enhanced Token Management: Providing built-in support for token rotation and expiration handling.
✅ Running Tests
Run tests using pytest:
pytest
🤝 Contributing
Contributions are welcome! If you'd like to contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature-branch) - Commit your changes (
git commit -m 'Add feature') - Push the branch (
git push origin feature-branch) - Open a pull request
For major changes, please open an issue first to discuss your ideas.
📄 License
This project is licensed under the MIT License. See the LICENSE file for more details.
📫 Contact
For questions and suggestions, feel free to reach out via GitHub Issues.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file drf_oauth_toolkit-0.1.2.tar.gz.
File metadata
- Download URL: drf_oauth_toolkit-0.1.2.tar.gz
- Upload date:
- Size: 16.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.5 CPython/3.13.1 Darwin/24.1.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
86af77fd545d45e5038c9eddf4753a11d706a5d1e7aec7db4d098e47f82b55d7
|
|
| MD5 |
1cd694a86a0e8de832b58af69df0428f
|
|
| BLAKE2b-256 |
002fca0750444a2b818e56aa84e436261c74345dfc2282f55c29d8c6f3fd6c5b
|
File details
Details for the file drf_oauth_toolkit-0.1.2-py3-none-any.whl.
File metadata
- Download URL: drf_oauth_toolkit-0.1.2-py3-none-any.whl
- Upload date:
- Size: 19.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.5 CPython/3.13.1 Darwin/24.1.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cc77944992c9587e4df80ef88a9ff49b0ab97bf169fe7379825ccf6dc34a93e1
|
|
| MD5 |
2493712a6911afb4957cb3bf3b04477a
|
|
| BLAKE2b-256 |
af7635f4bc55e1813f9ad6e06e742282035af91a812228f3941365b171686fda
|