Security - why should I care?

Let's say that you will want to make your REST-API available for others to use it. Let's face it - you will need to restrict use of API based on users. If you don't do that, you may face the reality of having issues with your data that's used by your API.

Let's play old game "What if".

You have your API for User accounts. You don't restrict access. What if someone discover API that you didn't published and reuse it in his own purpose ? i.e. for making dangerous calls that may lead to DATA LOSS ?

You may have some type of recovery mode (backups/snapshots), but what if this problem will not end in an "one-time-shot"?

So let's move to some possibilities to restrict access to your API !

What Django REST API can give out of the box?

In article - Authentication with Django-Rest-Framework you can find information how to add some security by using Authentication there.

There are :

  • BasicAuthentication
  • TokenAuthentication

For the purpose of checking out, I'll use the TokenAuthentication even if it's not best secure. But still it's available within rest-framework (out of the box thinking :) )

What are alternatives to django-rest-framework security?

Well there is a lot of frameworks that supports OAuth, but not all will natively support API.

Below you can check some of them that are mentioned at the "Authentication" article at Django-Rest-Framework:

Source code I've applied to Biking Endorphines.

At /bikingendorphines/api/models.py:

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)

At /bikingendorphines/bikingendorphines/settings.py:

# in `INSTALLED_APPS` this:
'rest_framework.authtoken',

# And added this

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

All I needed to do is create a new superuser and Grab Token from database, then apply it to requests like this (httpie in example used)

http GET 127.0.0.1:8000/api/user/ 'Authorization: Token XXXXX'

Final result

Check out my release for this article: 5-05-17 secure-api

Code commits done for this post:

Tools and applications used:

Acknowledgements

Django-Rest-Framework Token Authentication- at StackOverFlow

Accomplished:

1. How to secure biking-endorphines REST-API.

What's next

What's next

1. Plans for Biking-Endorphines

2. Badge Gathering source-code and tests.



Comments

comments powered by Disqus