How to Implement Custom Authentication with Django REST Framework

Posted by Chris Bartos on January 6, 2017

Introduction to Custom Authentication

Custom Authentication in Django REST Framework is the way you would create any time of authentication you would want. In fact, inside of the internals of DRF, you will find every other authentication scheme that I’ve talked about using CustomAuthentication. So, let’s look at an example of how you would implement something like this.

How to Implement Custom Authentication

WARNING: The example I’m about to show you is VERY VERY bad for security so DON’T use it in production. :)

First, you will need to override the BaseAuthentication class. It looks like this:

my_proj/accounts/auth.py

from django.contrib.auth.models import User
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions

class MyCustomAuthentication(BaseAuthentication):
    def authenticate(self, request):
        username = request.GET.get("username")

        if not username: # no username passed in request headers
            return None # authentication did not succeed

        try:
            user = User.objects.get(username=username) # get the user
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user') # raise exception if user does not exist

        return (user, None) # authentication successful

I called the new class MyCustomAuthentication. If you look at what this does, it retrieves a username as a GET request and will try to find a user with that username. (You should now understand why this is a stupid example).

Next, in settings.py you’ll want to update the DEFAULT_AUTHENICATION setting.

settings.py

REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (                             'accounts.auth.MyCustomAuthentication', ),
  'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }

And that is LITERALLY all you need to do to create a new authentication scheme. Download the custom code below and try going to the following URL:

http://localhost:8000/polls/api/questions/1/?username=chris

You should be able to see the data. Also, if you go to:

http://localhost:8000/polls/api/questions/1/

The authentication scheme should deny you from getting any data at all.

Click Here to Download the Sample Code

Homework

  1. Run the sample code and go to the two URLs above.
  2. Try to implement your own Session Authentication scheme WITHOUT enforcing CSRF tokens using Custom Authentication. You can see how Session Authentication is implemented here

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • and more...
Powered by ConvertKit

Django REST Framework Documentation got you down? Just want to get SOMETHING working?

You can learn Django REST Framework in ONE week at about 15 - 30 minutes per day (1 lesson per day for the next 7 days).

Click the button below to sign up and start learning Django REST Framework today!

click here to receive the first lesson in minutes!
(once you sign up, you'll get a new lesson everyday for the next 7 days)


Get some value from this post? Please like and share this post because more people also deserve some value. :-)