Category Archives: Authentication

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

3 Things You Need to Authenticate Users in Django

Published / by chris / Leave a Comment

You want to authenticate users but you’re unsure how. The documentation isn’t the most helpful thing in the world. You think, “wow… this documentation assumes I know all this other stuff…”

What are the things you need to authenticate users? There are 3 things you need and I’m going to show you what each looks like.

First: You need some routes

You need authentication routes. I think it makes the most sense to create a separate app for this purpose. (Separate all your login logic from all your other logic)

Let’s look at some login routes:

_loginapp/urls.py

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

from . import views

urlpatterns = [
    # Session Login
    url(r'^login/$', views.login_user, name='login'),
    url(r'^logout/$', views.logout_user, name='logout'),
    url(r'^auth/$',  views.login_form, name='login_form'),
]

Second: You’ll need some templates

Templates are important. Templates are the HTML representation of your application. For example, at the bare minimum, you’ll need a way to let your users login. How do you do it? It doesn’t have to be pretty because this is JUST HTML.

loginapp/templates/loginapp/login.html

<form method='post' action="{%  url 'loginapp:login' %}">
    <label for="username">Username:</label>
    <input type="text" name="username" />
    <br>
    <label for="password">Password:</label>
    <input type="password" name="password" />
    <br>
    <input type="submit" value="Login" />
</form>

Third: You’ll need some views

The views you’ll need for login will be:
1. The login form view (shows the login form)
2. The POST view that will authenticate a user that is active / exists
3. A view that will log the user out

Let’s start with the login form view (loginapp/auth):

def login_form(request):
    return render(request, 'accounts/login.html', {})

This view simply renders our login.html template that we created above. It’s also possible to make only 2 routes (1 that will detect a POST request and 1 that will detect a GET request) however, I (personally) really like have separate views for each request method.

Here is an example of a view that will detect a username and password and use those credentials to authenticate a user and login the user thus creating a session specifically for that user.

def login_user(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        # the password verified for the user
        if user.is_active:
            login(request, user)
            return redirect('/polls/')
    return redirect(settings.LOGIN_URL, request)

This method will get the username and password from the POST request data. Then, we will use the username and password to try to authenticate a user that exists in our database.

If a user exists, we will try to login our user and redirect to our polls application. If the user does not exist we will redirect back to the login form.

How do you logout an authenticated user?

def logout_user(request):
    logout(request)
    return redirect('/polls/')

This method will take the request object and user it to logout the logged in user. Once the user logs out, the application will redirect the user to our polls application.

This is the 3 things that you need to authenticate users in your Django application. (If you want to use Session Authentication with Django REST Framework) this is how you would accomplish this.

I hope that helps you when need to authenticate users in your future web application.

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

List of Authentication Schemes available for Django REST Framework

Published / by chris / Leave a Comment

Do you know what your options are?

You learned a little bit of how authentication works with Django REST Framework from my short, FREE mini email course. What you might NOT know is that Basic Authentication isn’t the only type of authentication available do you.

You can use the following authentication schemes in Django REST framework and keep checking your inbox for implementation details for each of these authentication schemes.

The list of Authentication types in Django REST Framework

  1. Basic Authentication — you learned how to implement this while following my free email course. If you haven’t signed up for the email course yet, put your email address in the form at the end of this post.
  2. Session Authentication — this is similar to the authentication that Django uses to authenticate users.
  3. Token Authentication — Token Auth is how most APIs authenticate users. You might have played around some APIs that require an “API Key”. This is how you would implement that for your users.
  4. Custom Authentication — If for some reason, the other authentication schemes don’t do what you want, you can override the BaseAuthentication class and create your own authentication scheme in Django REST Framework.
  5. OAuth2 Authentication — OAuth authentication is a way to allow your users to authenticate using things like Social Media. I’m sure you’ve logged into certain web apps that allowed you to authenticate using Google or Facebook. This allows you to do that!

Which Authentication scheme is best for me?

That will depend on your specific use case. If you know how to implement each of them, you’ll be better off in the long run. Come back to this post periodically. Each of the authentication schemes above will eventually link to a post that will show you EXACTLY how to implement each one.

If you’d rather not come back for each post, simply put your email in the box below and you’ll get every new post sent directly to your inbox!