Skip to content
This repository was archived by the owner on Sep 17, 2023. It is now read-only.

21 API Token Authentication

scotwk edited this page May 10, 2015 · 2 revisions

It's not always ideal to pass a password for an API. Configure Tastypie to use API keys. Also, we'll need to add a way to communicate the user's API key to them, so we will add a profile page.

Tastypie w/ API keys

In note/api/resources.py replace all instances of BasicAuthentication with ApiKeyAuthentication (there should be 3).

API key creation

We will make a "hook" so that whenever a new user is created an API key is generated for them. (We'll handle existing users in the next section)

In note/models.py, at the bottom of the file:

from tastypie.models import create_api_key

# Make a tastypie API key whenever a new user is created.
models.signals.post_save.connect(create_api_key, sender=User)

Generate keys

We'll put in a hook that makes a new API key for each new user, but to create keys for all the users who already exist run this command:

# Run migrate again because Tastypie needs to make a DB table to hold the keys
$ python manage.py migrate
$ python manage.py backfill_api_keys

Profile

In order to view your API key make use of the profile link in the top right. Create a new CBV using TemplateView and fetch the api_key in the get_context_data and pass it to the template to display.

class ProfileView(LoginRequiredMixin, NoteMixin, TemplateView):
    template_name = 'note/profile.html'
    
    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)
        
        try:
            api_key_obj = ApiKey.objects.get(user=self.request.user)
            api_key = api_key_obj.key
        except ApiKey.DoesNotExist:
            api_key = None

        context.update({
            'api_key': api_key
        })
        return context

Make sure to create a new URL entry for your profile view in note/urls.py

There is a profile template available at: https://github.com/sixfeetup/ElevenNote/raw/21-api-token-authentication/elevennote/note/templates/note/profile.html. Can you figure out where to put it?

Also, in note/templates/base.html update the Profile link so that it points at our new profile page. Make sure you use the same view name in here as you put in your URLs file.

<a href="{% url 'note:profile' %}">Profile</a>

Test

Once you know your API key you can use your browser like so: http://localhost:8000/api/v1/note/?format=json&username=scot&api_key=416d65381bcfb395ae7312c8028b7650b3413594

or the command like like so:

# Header format is "Authorization: ApiKey [username]:[api_key]"
$ curl --dump-header - -H "Authorization: ApiKey scot:416d65381bcfb395ae7312c8028b7650b3413594" http://localhost:8000/api/v1/note/?format=json

Clone this wiki locally