API Key Authentication with Django-Tastypie
For a particular project I am working on, I’ve decided to use the API key authentication (make sure you read this post if you are going to use this technique too) within django-tastypie as part of the protection mechanism on my RESTful API.
These are the notes I made when configuring this.
Tastypie uses its own table to store information, one of which is the apikey table. To make sure this is correctly configured, you need to:
o Add tastypie to your INSTALLED_APPS configuration (settings.py).
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'tastypie',
)
o Update your models.py so that it includes the tastypie extensions:
from django.contrib.auth.models import User
from django.db import models
from tastypie.models import create_api_key
...
models.signals.post_save.connect(create_api_key, sender=User)
This will also ensure that when a new user is added to your site that they will automatically get generated a new API key.
CAVEAT: If you make these changes before your site is created and then try to python manage.py syncdb
then you may run into some issues. Take a look at this page for a little more information.
Once this has been configured, the API key can be provided to the site in one of two ways:
o As a header, where the format is Authorization: ApiKey username:api_key
Authorization: ApiKey richard:204db7bcfafb2deb7506b89eb3b9b715b09905c8
o Or, alternatively, as GET params
http://127.0.0.1:8000/api/v1/list/?username=richardl%amp;api_key=204db7bcfafb2deb7506b89eb3b9b715b09905c8
Tweet |
|