Token Authentication Example

A snippet showing how to enable token authentication in DRF.


# settings.py
INSTALLED_APPS += ["rest_framework.authtoken"]

# Create tokens table
python manage.py migrate
      

# settings.py (REST_FRAMEWORK)

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
    ],
}
      

# urls.py - obtain token

from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path("api/token/", obtain_auth_token, name="api-token"),
]
      
Explanation:
  • POST username/password to /api/token/ to receive an auth token; include in 'Authorization: Token '.
Previous snippet
Router Example
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.