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

20 API Authentication

scotwk edited this page May 10, 2015 · 4 revisions

We will change our API back to the model where a user can only see their own notes.

First we need to deal with authentication. Then we need to handle authorization to indicate that a user can only view their own objects.

Authentication

In note/api/resources.py:

Import:

from tastypie.authentication import BasicAuthentication

Then add this into the Meta definitions for both resources:

authentication = BasicAuthentication()

BasicAuthentication uses the Django username/password combo.

You can read more about the authentication options here: http://django-tastypie.readthedocs.org/en/latest/authentication.html#authentication-options

Authorization

Now that we know we have a valid user (because of the authentication step above), we can restrict what a user is able to see.

First, create a new file at note/api/authorization.py

from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized


class UserObjectsOnlyAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        return object_list.filter(owner=bundle.request.user)

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return bundle.obj.owner == bundle.request.user

Note that this is only affecting GET requests. For more information on authorization see the docs here: https://django-tastypie.readthedocs.org/en/latest/authorization.html

Then, in note/api/resources.py use the new authorization class we created.

Import:

from .authorization import UserObjectsOnlyAuthorization

And add this line into the NoteResource definition:

    authorization = UserObjectsOnlyAuthorization()

Test

Try seeing someone else's notes at: http://localhost:8000/api/v1/note/?format=json&owner__username=SOMEONE_ELSE

It should return an empty list.