authentication

Explore Django REST Framework (DRF) authentication methods including SessionAuthentication, TokenAuthentication, and OAuth2. Learn how to implement and customize API authentication.

Django REST Framework Authentication

Understanding DRF Authentication

Django REST Framework (DRF) provides ready-to-use and integrated authentication schemes. If you require something more specific, you can customize your own scheme.

Session Authentication

SessionAuthentication utilizes Django's default session backend for authentication, which is highly practical for developers. Once a user is successfully authenticated, their User instance is stored in request.user.

Token Authentication

The TokenAuthentication class is recommended for client-server setups, such as native mobile applications.

To begin, add 'rest_framework.authtoken' to your INSTALLED_APPS:

INSTALLED_APPS = [
    # Rest of your installed apps ...
    'rest_framework',
    'rest_framework.authtoken'
]

Generating Tokens for Users

You can generate tokens for users using signals, typically defined in your models.py.

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

# For existing users
for user in User.objects.all():
    Token.objects.get_or_create(user=user)

# For newly created users
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

Obtaining Tokens via API

DRF includes a built-in view to obtain tokens by providing a username and password.

from rest_framework.authtoken import views
urlpatterns += [
    url(r'^api-token-auth/', views.obtain_auth_token)
]

OAuth and OAuth2 Integration

OAuth and OAuth2 were previously integrated directly into DRF. However, these modules have been moved and are now supported as third-party packages. Several other excellent and handy packages can also be easily implemented.

For more options, explore the third-party packages list.

Back to Top ↑