Category Archives: DRF

How to Override TokenAuthentication Backend to detect an expiring token

Published / by chris / Leave a Comment

Why would you want to keep your tokens around forever?

You don’t want to give away tokens that last forever when you’re authenticating because what that means for your users is that, if a token is stolen, an attacker will be able to login as long as your user’s token exists in the database. This is why JWT might seem to be “BETTER” than Token Authentication.

Token Auth with expiring tokens is a breeze

You definitely don’t know need to implement JWT in order to get the security of JWT. Token Authentication expiring tokens are a breeze and you’ll see the simplest way to implement them.

Determine how long you want your users to stay authenticated

This ends up being a question between usability, or how often would a user want to login and security. Obviously, you don’t want to keep a user logged in forever otherwise, an attacker could steal a user’s token and stay logged in on your user’s account forever.

On the other hand, it’s nice when you don’t have to continue to log in every time you want to to connect. When was the last time your had to log into Facebook?

A good rule of thumb is 2 weeks to 30 days.

Create a new Setting with that specific length of time

This is an arbitrary naming scheme that you can remember like, TOKEN_EXPIRE_TIME (or similar).

You always want to keep these constants in the setting.py file because you can update functionality in one place and it will automatically update how sections of your code works.

Here’s an example of setting expiring time:

settings.py

import datetime
TOKEN_EXPIRE_TIME=datetime.timedelta(days=30)

Override the TokenAuthentication Class to check validation

Now, you need to override the Token Authentication class so that every time Django REST Framework trying to authenticate you, our TokenAuthentication backend will check to see if your token is valid based on our TOKEN_EXPIRE_TIME setting.

So, here is our new backend. Remember to update your DEFAULT_AUTHENTICATION_CLASSES.

authentication.py

from rest_framework.authentication import TokenAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
import pytz

class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid token')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        utc_now = datetime.utcnow()
        utc_now = utc_now.replace(tzinfo=pytz.utc)

        if token.created < utc_now - settings.TOKEN_EXPIRE_TIME:
            raise exceptions.AuthenticationFailed('Token has expired')

        return token.user, token

Conclusion

This is an example of how you could override TokenAuthentication backend so that you can detect if your token is expired. The next thing you would need to do is create a new token for your users the next time they login.

Token Authentication can be a very robust authentication method. It’s up to you to figure out the best way to override Token Authentication to suit your needs because Token Authentication doesn’t do everything it should out of the box.

If you want to learn more about how to override Token Authentication so that it’s more robust, more secure and works better, you don’t have to guess any longer. I’m writing an ebook that will teach you these techniques in Token Authentication.

Want to learn more? Click here to learn about my book I’m writing. I’m launching soon! So, get it while it’s hot!

How to Implement OAuth2 using Django REST Framework

Published / by chris / Leave a Comment

Let’s paint a picture for you. You want to create a web and mobile application that allows your users to login more securely than Token Authentication. You know it’s possible, but you’re not sure how to implement something like this.

We can also use Facebook, Google, Twitter, Github, etc. to authenticate users. However, I’m just going to describe how to use OAuth to authenticate with JUST our application.

Maybe there is a package you can use? You’d be correct. There is a package you can use. OAuth Authentication implementation from scratch is complicated. Therefore, I recommend NOT re-inventing the wheel. I recommend using a package that already implements it. (I’ll write a post about how OAuth can be implemented yourself, if you’re interested in learning how this works).

I’m just going to pick a random OAuth package because it really doesn’t matter. The implementation of OAuth is the same no matter which package you choose. In this case, I’m going to use django-rest-framework-social-oauth2.

Implementing OAuth2 using Django-REST-Framework-Social-OAuth2

Let’s start by installing the package.

$ pip install django-rest-framework-social-oauth2

Now, let’s add the package apps to our INSTALLED_APPS.

settings.py

INSTALLED_APPS = (
    #...
    'oauth2_provider',
    'social_django',
    'rest_framework_social_oauth2,
)

Next, let’s include the URLs to our urls.py.

urls.py

urlpatterns = patterns(
    # ...
    url(r'^auth/', include('rest_framework_social_oauth2.urls')),
)

Now, we need to set up the packages CONTEXT_PROCESSORS. If you are using Django 1.8+ you’ll add the CONTEXT_PROCESSORS in the TEMPLATES setting.

settings.py

TEMPLATES = [
    {
        # ...
        'OPTIONS': {
            'context_processors': [
                # ...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    }
]

However, if you are using anything BEFORE Django 1.8, you’ll need to add the context processors like so…

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'social_django.context_processors.backends',
    'social_django.context_processors.login_redirect',
)

Now, we need some Authentication Backends so that Django and REST knows how to authenticate users. So, let’s add the backends to both settings.

settings.py

# DJANGO REST FRAMEWORK SETTINGS
REST_FRAMEWORK = {
    # ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # ...
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
}

# DJANGO SETTINGS 
AUTHENTICATION_BACKENDS = (
    # ...
    'rest_framework_social_oauth2.backends.DjangoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

Set up Web Application

We have successfully setup our application to use OAuth2 in our Web Application. Just like every time you add a new app to your list of INSTALLED_APPS, you always need to run:

$ python manage.py migrate

This command will build our database backend with the new models from the OAuth2 package.

Let’s run the application!

$ python manage.py runserver

If the application starts correctly, we’ll go to http://localhost:8000/admin/ and login with:

username: adminadmin 
password: adminadmin

When you login successfully, you’ll see a list of different options: Django OAuth Toolkit and Social_Django.

Underneath Django OAuth Toolkit, near Applications, click Add.

Your application should be filled out to be the following:

Client Id: **Do not change**
User: **click the hourglass and select the superuser**
Redirect URIs: **leave blank**
Client Type: “Confidential”
Authorization grant type: “Resource owner password-based”
Client secret: **Do not change**
Name: **Anything you want — maybe “Test Example”**

Next, click save to save that application.

Test the Application

Use either CURL (command line) or use Postman to create a POST request to your web application (http://localhost:8000/auth/token using the following information:

username=adminadmin
password=adminadmin
client_id=QKaPafSal2lYYfIYIDSKCC3hoj0TRPLFnZYJNE0h
client_secret=bvQDk9bIwVS28VSNZFP5ehgsrnQroWP5xHccdradOvqxonWSqC1soy7HzaiIiRzCQi73o0pPKyWp7dEoS8DgrZWLoiwJf7iZ8kymv1rb1s3Hx3XSTGQgDmVBqveOQT5H
grant_type=password

If you are using CURL, you can run the following command:

$ curl -X POST -d "client_id=QKaPafSal2lYYfIYIDSKCC3hoj0TRPLFnZYJNE0h&client_secret=bvQDk9bIwVS28VSNZFP5ehgsrnQroWP5xHccdradOvqxonWSqC1soy7HzaiIiRzCQi73o0pPKyWp7dEoS8DgrZWLoiwJf7iZ8kymv1rb1s3Hx3XSTGQgDmVBqveOQT5H&grant_type=password&username=adminadmin&password=adminadmin" http://localhost:8000/auth/token

If you are using Postman, your interface should look like this:

This will retrieve a secret token for use for authentication by our user.

Now, we need to use the access token that we received and create an Authorization header in the form:

Authorization: Bearer [access_token]

The access token that I received happens to look like this: 71AVaiCidnYcD2ct3Mqgat9j4jo6Xl.

So, if I want to access http://localhost:8000/polls/api/questions/1 I have to create a header using my access token in order to access that question.

In CURL, I would do something like this:

$ curl -H "Authorization: Bearer 71AVaiCidnYcD2ct3Mqgat9j4jo6Xl" -X GET http://localhost:8000/polls/api/questions/1

In Postman I do something like this:

Just to test it out to make sure that I’m doing this right, I will remove the Header from the request and see if Django will let me access the data. Not surprisingly, it doesn’t let me in!

Click here for my Sample Code — remember to install the package using pip

Homework (because this helps you apply what you learned)

  1. Setup a new Django REST Framework web application
  2. Add an endpoint, a serializer and make sure only authenticated users can access the data.
  3. Follow the steps above and try OAuth2 out for yourself. Get it to work.
  4. If you have questions email me

Now, you know how to implement OAuth2 in your own application. You can use the similar steps to get this setup for Facebook, Google, Twitter, Github, etc. so you can allow users to sign in to your application using accounts that they already have and use!

Try this out, see if you can get it work for yourself!

How to Implement Token Authentication with Django REST Framework

Published / by chris / 5 Comments on How to Implement Token Authentication with Django REST Framework

Token Authentication seems to be an Authentication Scheme that gives people the most trouble. The reason appears to be a misunderstanding not of so much how to implement it, but how to actually use it.

For example, the Django REST Framework documentation says that for every request, you have to add an Authorization Header to your requests. But, how do you create that Authorization header?

Also…

How do I use Token Authentication to authorize external clients? These are serious questions that I’ve seen from people just like you. But, the difference is that after reading this post, you’ll understand how that works. I’ll show you how to implement Token Authentication using Django REST Framework. Then, I’ll give you a sample application that uses Token Authentication to authenticate users within a Django Application. Best of all, you can take what you learn from my sample code to use in external clients (Javascript clients) to authenticate / authorize users with your RESTful API.

WARNING: NEVER, EVER use Token Authentication without using Secure HTTP (HTTPS). If you want to run my sample code or play around with your own code locally it is OKAY to use Unsecure HTTP (HTTP). However, NEVER do it in production. You’ve been warned.

Introduction to Token Authentication

Token Authentication is a way to authorize users by using an API Key or Auth Token. The way Django REST Framework implements Token Authentication requires you to add a header for each request. This header will be in the following format:

Authorization: Token 93138ba960dfb4ef2eef6b907718ae04400f606a

Authorization is the header key and Token 93138ba960dfb4ef2eef6b907718ae04400f606a is the header value. Note, there is a space between Token and the token itself.

The server where your API lives will read off the user’s token and determine if there is a user assigned to that particular token.

This is Token Authentication in a nutshell. It really doesn’t get anymore complicated than that. The difficulty is implementing it for each of the clients that will use the API (Javascript apps, Desktop apps, Commandline, etc.)

How to Implement Token Authentication

The implementation is a bit more complicated than other Authentication Schemes so take this slow, digest each piece of the puzzle and make sure to download my sample code so you can see what I’m doing each step of the way.

Preliminary Configuration

As with all Django REST Framework Authentication schemes, you must configure the authentication scheme that you will use in your settings.py file.

myproject/settings.py

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

This is where it’s a little different than other Authentication schemes. You will also need to add an app to your INSTALLED_APPS array. The reason for this is because Token Authentication requires a special model called Token which is used to store your user authentication tokens.

In my sample application, my INSTALLED_APPS tuple looks like this:

myproject/settings.py

INSTALLED_APPS = ( 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles',
    'polls',
    'accounts',
    'rest_framework',
    'rest_framework.authtoken',
)

Now, in order to install the app and update the database with the new Token model, it is imperative that we run python manage.py migrate.

Now, you should be ready to create tokens for your users, create a post_save method on your User model so that whenever a new user is added to your database it will automatically create a token for them.

Create Tokens for your Users

Go to your project shell by typing this command at a terminal: python manage.py shell. You should be presented with a prompt that looks like this: >>>.

Now, you’re going to type in the following code:

from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

users = User.objects.all()
for user in users:
    token, created = Token.objects.get_or_create(user=user)
    print user.username, token.key

This code will retrieve all the users that currently exist in your database. It loops through each of them, generates a unique token for each of them and prints our their username and their token. It’s nice to print out their username and the token so you can see that it in fact worked correctly.

Now, you don’t want to manually create tokens for your users whenever a new user registers for your web app so you’ll have to create a special function that will automatically create a token for each new user:

myproject/accounts/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 

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

Now, every time a new user is saved in your database, this function will run and a new Token will be created for that user.

Create a Route for Retrieving a Token for Successfully logged in users

Django REST Framework provides a view that simply returns the user’s token when they provide a correct username / password combo.

Let’s add this now:

myproject/accounts/urls.py

from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static

from . import views as local_view
from rest_framework.authtoken import views as rest_framework_views

urlpatterns = [ 
    # Session Login
    url(r'^login/$', local_views.get_auth_token, name='login'),
    url(r'^logout/$', local_views.logout_user, name='logout'),
    url(r'^auth/$', local_views.login_form, name='login_form'),
    url(r'^get_auth_token/$', rest_framework_views.obtain_auth_token, name='get_auth_token'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

The bottom route is what you should notice:

url(r'^get_auth_token/$', rest_framework_views.obtain_auth_token, name='get_auth_token'),

Now, when POST’ing to http://localhost:8000/accounts/get_auth_token/ with the following data (assuming this username / password exists): { 'username': 'admin', 'password': 'admin' } you’ll receive something that looks like the following: { 'token': '93138ba960dfb4ef2eef6b907718ae04400f606a' }

You’re done implementing Token Authentication. So, what can you do with this Authentication Scheme? Whatever you want. Let’s look at some sample code to see how this works.

I’m launching my e-book very shortly (March 10, 2017). To get additional information, click here.

Click Here to Download the Sample Code

How to use the Sample Code

  1. Unzip the code repository
  2. Change directory to the unzipped code repository
  3. Run the command python manage.py runserver
  4. Go to http://localhost:8000/polls/ to run the code.
  5. You’ll be redirected to a very crude login form
  6. Type admin for the username and admin for the password
  7. You’ll be redirected to the polls app and application should work.
  8. Go to http://localhost:8000/accounts/logout to invalidate the cookie that holds the Authentication Token.
  9. Download Postman from https://www.getpostman.com/
  10. Open Postman. Make sure the dropdown says, “GET”.
  11. Type in: http://localhost:8000/polls/api/questions/1 into the address bar.
  12. Make sure under Authorization “No Auth” is selected.
  13. Under “Headers” add the Header key: Content-Type. Make the Header value: application/json
  14. Click “Send” and you should retrieve "Authentication credentials were not provided."
  15. Now, under “Headers” underneath “Content-Type” add the Header key: Authorization and add the Header value: “Token 93138ba960dfb4ef2eef6b907718ae04400f606a” (without the quotes).
  16. Click “Send” again and you should be getting the correct data.

Homework (If you’d like…)

  1. Look at ALL of my sample code.
    • Underneath the admin form in login.html there is some Javascript that creates a call to http://localhost:8000/accounts/get_auth_token/ with my username and password. When I retrieve the token, I put it into a cookie called “token” and I redirect to the ‘/polls/‘ app.
    • In the app.js file (where my AngularJS code lives), I created an “Interceptor”. The purpose of it is to intercept requests and automatically add a Header with your token so that the Polls Application works correctly. If a request fails, it assumes the user isn’t authorized and redirects to the login form.
  2. Play around with Postman. As long as you keep the Authorization header you can run through the API endpoints and see what you get.
  3. Play with Python Requests. Keep the Django Application running and see if you can write a program using Python Requests that will allow you to login and retrieve some information.

The homework is to help you understand why you would want to use Token Authentication. You can create cool applications external to the Django Application that interface with your API. Give it a go and see what you come up with!

Until next time, Chris

How do I Implement Session Authentication in Django REST Framework?

Published / by chris / Leave a Comment

Introduction to Session Authentication

Session Authentication when used with Django REST Framework allows you to authenticate users very similar to the way Django authenticates users without Django REST Framework.

This will make it extremely easy to introduce a REST API to your web app without having to completely overhaul your authentication system.

The best part of this Authentication Scheme is you literally only have to change ONE line of your Django Application.

Implementation Details (all the little bits…)

In your settings.py file, just add 'rest_framework.authentication.SessionAuthentication', to your DEFAULT_AUTHENTICATION_CLASSES setting.

myproject/settings.py

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

Now, you will be able to login using the normal Django Framework login views / templates, etc or create your own like I did in my sample application below. Also, here is a post about how I like to create authentication in Django.

If you’d like an example of how this is accomplished, I’ve updated the Django Application I used to show you how to implement Basic Authentication using Django REST Framework. Now, it works using Session Authentication.

Click Here to Download the Sample Code

How to use this Sample Code

  1. Unzip the code repository
  2. Change directory to the unzipped code repository
  3. Run the command python manage.py runserver
  4. Go to http://localhost:8000/polls/ to run the code.
  5. You’ll be redirected to a very crude login form
  6. Type admin for the username and admin for the password
  7. You’ll be redirected to the polls app and application should work.
  8. Go to http://localhost:8000/accounts/logout to logout of your session.
  9. Go to http://localhost:8000/polls/api/questions/1 to checkout the API (it should tell you that you’re not authenticated to look at the data).
  10. Go to http://localhost:8000/accounts/login and login with admin for the username and admin for the password.
  11. Go back to http://localhost:8000/polls/api/questions/1 and you should be able to see the data now that you are signed in.
  12. My login routes, views and templates are found in my accounts app.

That is the Session Authentication Scheme in a nutshell. I hope you realize how simple it is to implement. Now… for some homework!

Homework (If you’d like…)

  1. Use the sample application and change the static login form into an AJAX style form. (So, when you put in admin for the username and password and click login there should be an AJAX POST request with the username, password and CSRF Token that will attempt to login the user and either send a success message or a failure message. Then, redirect the user back to the /polls/. If you’re unsure how to add a CSRF Token to all AJAX requests, sign up for my FREE Django REST Framework email course below.)

Want to learn how to Implement Token Authentication in Django REST Framework

Why Do You Want to Learn Django REST Framework?

Published / by chris / Leave a Comment

If you do a tiny bit of lurking on Django forums, it seems like EVERYBODY is going nuts over learning how to create a RESTful API in Django using Django REST Framework. I’m fastinated by this craze. So, I wanted to start a conversation about why YOU might want to learn how to create a RESTful API.

You might want to pay attention, I have a fun surprise at the end of this post.

So, you crazy people and your new fangled RESTful API technologies, need to understand what you need to know about REST and why it might make sense to use it.

Reasons for creating an API

You have probably heard about REST and APIs while reading about how that cool new tech startup created that amazing website. It seems like everything COOL online is written in pure Javascript.

That awesome Single Page Application looks so cool how it feels like a desktop application. It’s seamless, it’s fast and I want to do that SAME THING!!

Besides creating cool apps, here is why you might want to learn REST and Django REST Framework for that matter.

1. Domain Independence

If you only had a REST API, what would you be able to do with it?

Maybe you want to integrate your web presence into a mobile app. You can use your API to make your app do all the cool things your web app can do, but now you have piece of software people can install into their phones and get all your snazzy widgets quicker and easier than ever!

What if you wanted to create a desktop application (Not sure why you would…) but, you’d be able to send data back to your server directly from your amazing software.

Some people and companies even sell usage for their API. You could potentially charge people to use your API so they can create their own awesome apps.

Literally, the sky is the limit.

2. Programming Language Independence

This falls in line with the above. Think you need to follow the same programming language to get your REST API working in other domains? For example, if you’re using Django to create your REST API, do you need to use Django to work with it? Absolutely not!

You could use any programming language and integrate your API with it.

  • Create an Android App using Java
  • Create an iOS App using Objective-C or Swift
  • Create a Desktop application using Python or C++
  • Create a Single Page Application with your API using Javascript
  • The choice is yours!

3. It scales great!

You can layer as much as you need between client and server. Want a load balancer? Caching Mechanism? Special routing needs?

It’s not difficult to get things working with a REST API.

Just a reminder, don’t forget that if you’re using the REST API for too many things, you’ll definitely have problems with bandwidth and latency issues.

Doesn’t REST Sound Fun?

I hope the above helps you decide if you should be learning Django REST Framework. It’s a lot of fun and you can do SO MUCH with it!

If for nothing else but to put on your resume that you understand how to create RESTful APIs and some experience with Django REST Framework, I’ve created an email course that will walk you through creating an API with Django REST Framework.

You’ll learn how to take that “Polls App” that you created with the Official Django Tutorial and we are going to extend it with a RESTful API.

Then, as a special BONUS lesson, you will learn how to USE the API using AngularJS because, why LEARN to create a RESTful API if you don’t know how to use it? Am I right?!

Sign up below! The first lesson will reach your inbox shortly!!