{"id":5910,"library":"django-rest-knox","title":"django-rest-knox: DRF Token Authentication","description":"django-rest-knox provides robust token-based authentication for Django REST Framework. It supports multiple tokens per user, token expiration, and single-token or all-token logout functionality. Maintained by Jazzband, the library is actively developed, with its current version being 5.0.4.","status":"active","version":"5.0.4","language":"en","source_language":"en","source_url":"https://github.com/jazzband/django-rest-knox","tags":["django","drf","rest-framework","authentication","token","knox","security"],"install":[{"cmd":"pip install django-rest-knox","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Core functionality relies on Django REST Framework components.","package":"djangorestframework","optional":false},{"reason":"Django is the underlying web framework.","package":"django","optional":false}],"imports":[{"symbol":"TokenAuthentication","correct":"from knox.auth import TokenAuthentication"},{"symbol":"AuthToken","correct":"from knox.models import AuthToken"},{"symbol":"LoginView","correct":"from knox.views import LoginView"},{"symbol":"LogoutView","correct":"from knox.views import LogoutView"},{"symbol":"LogoutAllView","correct":"from knox.views import LogoutAllView"}],"quickstart":{"code":"import os\nimport django\nfrom django.conf import settings\nfrom django.urls import path, include\nfrom django.http import JsonResponse\n\n# Minimal Django settings for quickstart\nif not settings.configured:\n    settings.configure(\n        DEBUG=True,\n        INSTALLED_APPS=[\n            'django.contrib.admin',\n            'django.contrib.auth',\n            'django.contrib.contenttypes',\n            'rest_framework',\n            'knox',\n        ],\n        SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-dev'),\n        ROOT_URLCONF=__name__,\n        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},\n        REST_FRAMEWORK={\n            'DEFAULT_AUTHENTICATION_CLASSES': [\n                'knox.auth.TokenAuthentication',\n            ]\n        },\n    )\n\ndjango.setup()\n\nfrom rest_framework import permissions\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom knox.views import LoginView as KnoxLoginView, LogoutView, LogoutAllView\nfrom django.contrib.auth.models import User # For example purposes\n\n# Create a dummy user for testing\nif not User.objects.filter(username='testuser').exists():\n    User.objects.create_user(username='testuser', email='test@example.com', password='password123')\n\ndef hello_view(request):\n    return JsonResponse({'message': 'Hello, API!', 'user': str(request.user), 'authenticated': request.user.is_authenticated})\n\nurlpatterns = [\n    # Knox authentication URLs\n    path('api/auth/login/', KnoxLoginView.as_view(), name='knox_login'),\n    path('api/auth/logout/', LogoutView.as_view(), name='knox_logout'),\n    path('api/auth/logoutall/', LogoutAllView.as_view(), name='knox_logoutall'),\n    \n    # Protected example view\n    path('api/hello/', hello_view, name='hello'),\n]\n\n# To run: \n# 1. Save as a .py file (e.g., quickstart.py)\n# 2. python manage.py makemigrations knox (if you create a new project structure)\n# 3. python manage.py migrate\n# 4. Create a superuser: python manage.py createsuperuser (or use the dummy user created above)\n# 5. python manage.py runserver\n#\n# Test with curl:\n# Login (creates token):\n# curl -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"testuser\", \"password\":\"password123\"}' http://127.0.0.1:8000/api/auth/login/\n# \n# Access protected endpoint with token (replace YOUR_TOKEN_VALUE):\n# curl -H \"Authorization: Token YOUR_TOKEN_VALUE\" http://127.0.0.1:8000/api/hello/\n# \n# Logout:\n# curl -X POST -H \"Authorization: Token YOUR_TOKEN_VALUE\" http://127.0.0.1:8000/api/auth/logout/\n","lang":"python","description":"To integrate `django-rest-knox`:\n1. Add `knox` to your `INSTALLED_APPS`.\n2. Add `knox.auth.TokenAuthentication` to `REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']`.\n3. Include `knox.urls` in your project's `urls.py`.\n4. Optionally, create a custom `LoginView` or use `knox.views.LoginView` directly to handle user login and token creation. The example demonstrates a minimal Django setup with a `LoginView` and a protected endpoint."},"warnings":[{"fix":"Users will need to log in again to generate new tokens after upgrading to 5.0.0 or later.","message":"Tokens created prior to django-rest-knox 5.0.0 are no longer valid due to internal changes in token generation and storage.","severity":"breaking","affected_versions":"<5.0.0"},{"fix":"Update any custom code that calls `AuthToken.objects.create()` to expect the new return tuple and adjust references from `expires` to `expiry` on `AuthToken` instances. A migration is required.","message":"The `create()` method on the `AuthToken` model changed its signature and return value in 4.0.0. It now returns `(instance, token)` instead of just `token`. Additionally, the `AuthToken` model field `expires` was renamed to `expiry`.","severity":"breaking","affected_versions":"<4.0.0"},{"fix":"Run `python manage.py makemigrations knox` and `python manage.py migrate` after upgrading to 4.2.0 or later to apply the schema changes correctly.","message":"The `salt` field of the `AuthToken` model was removed in version 4.2.0. This change requires a migration.","severity":"breaking","affected_versions":"<4.2.0"},{"fix":"Upgrade to 5.0.4 or later. If unable to upgrade, consider prefetching or selecting related users when querying `AuthToken` objects to mitigate N+1 queries manually.","message":"Potential N+1 query issue fixed in 5.0.4 on `AuthToken.user` access. Older versions might suffer performance degradation in scenarios retrieving tokens and accessing their associated users.","severity":"gotcha","affected_versions":"<5.0.4"},{"fix":"Set `AUTO_REFRESH_MAX_TTL` in your `settings.py` (e.g., `KNOX = {'AUTO_REFRESH_MAX_TTL': timedelta(hours=24)}`) when `AUTO_REFRESH` is enabled to enforce a maximum token lifespan. Ensure you're on version 5.0.2 or newer.","message":"If `AUTO_REFRESH = True`, tokens could theoretically live forever. Version 5.0.2 introduced `AUTO_REFRESH_MAX_TTL` to limit the total lifetime of such tokens.","severity":"gotcha","affected_versions":"<5.0.2 (when AUTO_REFRESH is true)"},{"fix":"Upgrade to 5.0.2 or later to get the fix for this migration issue.","message":"A migration issue existed in 5.0.1 when not overriding the `AuthToken` model, which could prevent migrations from running correctly.","severity":"gotcha","affected_versions":"5.0.1"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}