Tuesday, 5 September 2017

Django REST Framework's Token Based Authentication

Do the following things BEFORE you create the superuser. Otherwise, the superuser does not get his/her token created.

 

INSTALLED_APPS = (
    'rest_framework',
    'rest_framework.authtoken',
    'myapp',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}


Alternatively, if you want to be more explicit, create a file named signals.py under myapp project. Put the code above in it, then in init.py, write import signals

Improvements

DRF's token implementation lacks a few important features:
  • Tokens do not rotate
  • Tokens do not expire
  • The same token is shared among all the clients (PC browsers, smartphones, tablets, etc.)
The Django Oauth Toolkit should be considered as a step up.
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings

# This code is triggered whenever a new user has been created and saved to the database

@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)

Google’s TGIF (Thank God It’s Friday)

Google’s TGIF ( Thank God It’s Friday ) meetings were a long-standing tradition within the company, serving as weekly all-hands meetings whe...