Getting started

Django OAuth Toolkit provide a support layer for Django REST Framework. This tutorial is based on the Django REST Framework example and shows you how to easily integrate with it.

NOTE

The following code has been tested with Django 2.0.3 and Django REST Framework 3.7.7

Step 1: Minimal setup

Create a virtualenv and install following packages using pip…

  1. pip install django-oauth-toolkit djangorestframework

Start a new Django project and add ‘rest_framework’ and ‘oauth2_provider’ to your INSTALLED_APPS setting.

  1. INSTALLED_APPS =(
  2. 'django.contrib.admin',
  3. ...
  4. 'oauth2_provider',
  5. 'rest_framework',
  6. )

Now we need to tell Django REST Framework to use the new authentication backend. To do so add the following lines at the end of your settings.py module:

  1. REST_FRAMEWORK ={
  2. 'DEFAULT_AUTHENTICATION_CLASSES':(
  3. 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
  4. )
  5. }

Step 2: Create a simple API

Let’s create a simple API for accessing users and groups.

Here’s our project’s root urls.py module:

  1. from django.urls import path, include
  2. from django.contrib.auth.models importUser,Group
  3. from django.contrib import admin
  4. admin.autodiscover()
  5. from rest_framework import generics, permissions, serializers
  6. from oauth2_provider.contrib.rest_framework importTokenHasReadWriteScope,TokenHasScope
  7. # first we define the serializers
  8. classUserSerializer(serializers.ModelSerializer):
  9. classMeta:
  10. model =User
  11. fields =('username','email',"first_name","last_name")
  12. classGroupSerializer(serializers.ModelSerializer):
  13. classMeta:
  14. model =Group
  15. fields =("name",)
  16. # Create the API views
  17. classUserList(generics.ListCreateAPIView):
  18. permission_classes =[permissions.IsAuthenticated,TokenHasReadWriteScope]
  19. queryset =User.objects.all()
  20. serializer_class =UserSerializer
  21. classUserDetails(generics.RetrieveAPIView):
  22. permission_classes =[permissions.IsAuthenticated,TokenHasReadWriteScope]
  23. queryset =User.objects.all()
  24. serializer_class =UserSerializer
  25. classGroupList(generics.ListAPIView):
  26. permission_classes =[permissions.IsAuthenticated,TokenHasScope]
  27. required_scopes =['groups']
  28. queryset =Group.objects.all()
  29. serializer_class =GroupSerializer
  30. # Setup the URLs and include login URLs for the browsable API.
  31. urlpatterns =[
  32. path('admin/', admin.site.urls),
  33. path('o/', include('oauth2_provider.urls',namespace='oauth2_provider')),
  34. path('users/',UserList.as_view()),
  35. path('users/<pk>/',UserDetails.as_view()),
  36. path('groups/',GroupList.as_view()),
  37. # ...
  38. ]

Also add the following to your settings.py module:

  1. OAUTH2_PROVIDER ={
  2. # this is the list of available scopes
  3. 'SCOPES':{'read':'Read scope','write':'Write scope','groups':'Access to your groups'}
  4. }
  5. REST_FRAMEWORK ={
  6. # ...
  7. 'DEFAULT_PERMISSION_CLASSES':(
  8. 'rest_framework.permissions.IsAuthenticated',
  9. )
  10. }

OAUTH2_PROVIDER.SCOPES setting parameter contains the scopes that the application will be aware of, so we can use them for permission check.

Now run the following commands:

  1. python manage.py migrate
  2. python manage.py createsuperuser
  3. python manage.py runserver

The first command creates the tables, the second creates the admin user account and the last one runs the application.

Next thing you should do is to login in the admin at

  1. http://localhost:8000/admin

and create some users and groups that will be queried later through our API.

Step 3: Register an application

To obtain a valid access_token first we must register an application. DOT has a set of customizable views you can use to CRUD application instances, just point your browser at:

  1. http://localhost:8000/o/applications/

Click on the link to create a new application and fill the form with the following data:

  • Name: just a name of your choice
  • Client Type: confidential
  • Authorization Grant Type: Resource owner password-based

Save your app!

Step 4: Get your token and use your API

At this point we’re ready to request an access_token. Open your shell

  1. curl -X POST -d "grant_type=password&username=<user_name>&password=<password>"-u"<client_id>:<client_secret>" http://localhost:8000/o/token/

The user_name and password are the credential of the users registered in your Authorization Server, like any user created in Step 2. Response should be something like:

  1. {
  2. "access_token":"<your_access_token>",
  3. "token_type":"Bearer",
  4. "expires_in":36000,
  5. "refresh_token":"<your_refresh_token>",
  6. "scope":"read write groups"
  7. }

Grab your access_token and start using your new OAuth2 API:

  1. # Retrieve users
  2. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/
  3. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/
  4. # Retrieve groups
  5. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/groups/
  6. # Insert a new user
  7. curl -H "Authorization: Bearer <your_access_token>"-X POST -d"username=foo&password=bar" http://localhost:8000/users/

Some time has passed and your access token is about to expire, you can get renew the access token issued using the refresh token:

  1. curl -X POST -d "grant_type=refresh_token&refresh_token=<your_refresh_token>&client_id=<your_client_id>&client_secret=<your_client_secret>" http://localhost:8000/o/token/

Your response should be similar to your first access_token request, containing a new access_token and refresh_token:

  1. {
  2. "access_token":"<your_new_access_token>",
  3. "token_type":"Bearer",
  4. "expires_in":36000,
  5. "refresh_token":"<your_new_refresh_token>",
  6. "scope":"read write groups"
  7. }

Step 5: Testing Restricted Access

Let’s try to access resources using a token with a restricted scope adding a scope parameter to the token request

  1. curl -X POST -d "grant_type=password&username=<user_name>&password=<password>&scope=read"-u"<client_id>:<client_secret>" http://localhost:8000/o/token/

As you can see the only scope provided is read:

  1. {
  2. "access_token":"<your_access_token>",
  3. "token_type":"Bearer",
  4. "expires_in":36000,
  5. "refresh_token":"<your_refresh_token>",
  6. "scope":"read"
  7. }

We now try to access our resources:

  1. # Retrieve users
  2. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/
  3. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/

Ok, this one works since users read only requires read scope.

  1. # 'groups' scope needed
  2. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/groups/
  3. # 'write' scope needed
  4. curl -H "Authorization: Bearer <your_access_token>"-X POST -d"username=foo&password=bar" http://localhost:8000/users/

You’ll get a “You do not have permission to perform this action” error because your access_token does not provide the required scopes groups and write.