4 - Authentication and Permissions - Django REST Framework
4 - Authentication and Permissions - Django REST Framework
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the
pygments code highlighting library.
When that's all done we'll need to update our database tables. Normally we'd create a database migration in
order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm -f db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate
You might also want to create a few different users, to use for testing the API. The quickest way to do this will
be with the createsuperuser command.
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects
class Meta:
model = User
fields = ['id', 'username', 'snippets']
Because 'snippets' is a reverse relationship on the User model, it will not be included by default when
using the ModelSerializer class, so we needed to add an explicit field for it.
We'll also add a couple of views to views.py . We'd like to just use read-only views for the user
representations, so we'll use the ListAPIView and RetrieveAPIView generic class-based views.
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to
the patterns in snippets/urls.py .
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
The way we deal with that is by overriding a .perform_create() method on our snippet views, that allows
us to modify how the instance save is managed, and handle any information that is implicit in the incoming
request or requested URL.
The create() method of our serializer will now be passed an additional 'owner' field, along with the
validated data from the request.
owner = serializers.ReadOnlyField(source='owner.username')
Note: Make sure you also add 'owner', to the list of fields in the inner Meta class.
This field is doing something quite interesting. The source argument controls which attribute is used to
populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation
shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's
template language.
The field we've added is the untyped ReadOnlyField class, in contrast to the other typed fields, such as
CharField , BooleanField etc... The untyped ReadOnlyField is always read-only, and will be used for
serialized representations, but will not be used for updating model instances when they are deserialized. We
could have also used CharField(read_only=True) here.
REST framework includes a number of permission classes that we can use to restrict who can access a given
view. In this case the one we're looking for is IsAuthenticatedOrReadOnly , which will ensure that
authenticated requests get read-write access, and unauthenticated requests get read-only access.
Then, add the following property to both the SnippetList and SnippetDetail view classes.
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py
file.
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
The 'api-auth/' part of pattern can actually be whatever URL you want to use.
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page.
If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the
representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets'
field.
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
Now we can add that custom permission to our snippet instance endpoint, by editing the
permission_classes property on the SnippetDetail view class:
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet
instance endpoint if you're logged in as the same user that created the code snippet.
When we interact with the API through the web browser, we can login, and the browser session will then
provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials
on each request.
{
"detail": "Authentication credentials were not provided."
}
We can make a successful request by including the username and password of one of the users we created
earlier.
{
"id": 1,
"owner": "admin",
"title": "foo",
"code": "print(789)",
"linenos": false,
"language": "python",
"style": "friendly"
}
Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system
and for the code snippets that they have created.
In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our
highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within
the system.
Documentation built with MkDocs.