DRF Token Authentication Tutorial

All we need is an easy explanation of the problem, so here it is.

I am pretty new to Django, but I want to learn how to implement a DRF Token Authentication with Angularjs. Some of the tutorials I have found haven’t been too helpful in showing how to set it up, along with their source code etc…

Also, for production purposes, is it more practical to use a third party package? Or set up my own (it’s for a personal project, so time contribution is not an issue).

My Buggy Code for Token Auth: Github

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In settings.py

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

In signals.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

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

In views.py

class ExampleAuthToken(APIView):
    def post(self, request, format=None):
        username = request.data.get("username")
        password = request.data.get("password")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create_user(username=username)
            user.set_password(password)
            user.save()
        content = {
            'user': unicode(user.username),
            'token': unicode(user.auth_token),
        }
        return Response(content)

In urls.py

urlpatterns = [
    url(r'^authtoken/', ExampleAuthToken.as_view(), name='authtoken'),
]

To call using the angularjs;

var credentials = {
  username: "root",
  password: "root123"
};

$.post("http://localhost:8000/authtoken/", credentials {
    success: function(data){
          console.log(data);
    }
}

Method 2

I would definitely use a library. For token authentication there is the nifty django-rest-framework-jwt – it’s straightforward to install and setup. To help with Angular JS looks like there is drf-angular-jwt (which uses DRF-JWT but I have not used it).

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply