Getting started

Django OAuth Toolkit provide a support layer forDjango 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 usingpip:

pipinstalldjango-oauth-toolkitdjangorestframework

Start a new Django project and add'rest_framework' and'oauth2_provider' to yourINSTALLED_APPS setting.

INSTALLED_APPS=('django.contrib.admin',...'oauth2_provider','rest_framework',)

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 yoursettings.py module:

REST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':('oauth2_provider.contrib.rest_framework.OAuth2Authentication',)}

Step 2: Create a simple API

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

Here’s our project’s rooturls.py module:

fromdjango.urlsimportpath,includefromdjango.contrib.auth.modelsimportUser,Groupfromdjango.contribimportadminadmin.autodiscover()fromrest_frameworkimportgenerics,permissions,serializersfromoauth2_providerimporturlsasoauth2_urlsfromoauth2_provider.contrib.rest_frameworkimportTokenHasReadWriteScope,TokenHasScope# first we define the serializersclassUserSerializer(serializers.ModelSerializer):classMeta:model=Userfields=('username','email',"first_name","last_name")classGroupSerializer(serializers.ModelSerializer):classMeta:model=Groupfields=("name",)# Create the API viewsclassUserList(generics.ListCreateAPIView):permission_classes=[permissions.IsAuthenticated,TokenHasReadWriteScope]queryset=User.objects.all()serializer_class=UserSerializerclassUserDetails(generics.RetrieveAPIView):permission_classes=[permissions.IsAuthenticated,TokenHasReadWriteScope]queryset=User.objects.all()serializer_class=UserSerializerclassGroupList(generics.ListAPIView):permission_classes=[permissions.IsAuthenticated,TokenHasScope]required_scopes=['groups']queryset=Group.objects.all()serializer_class=GroupSerializer# Setup the URLs and include login URLs for the browsable API.urlpatterns=[path('admin/',admin.site.urls),path('o/',include(oauth2_urls)),path('users/',UserList.as_view()),path('users/<pk>/',UserDetails.as_view()),path('groups/',GroupList.as_view()),# ...]

Also add the following to yoursettings.py module:

OAUTH2_PROVIDER={# this is the list of available scopes'SCOPES':{'read':'Read scope','write':'Write scope','groups':'Access to your groups'}}REST_FRAMEWORK={# ...'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',)}LOGIN_URL='/admin/login/'

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:

pythonmanage.pymigratepythonmanage.pycreatesuperuserpythonmanage.pyrunserver

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

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

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 customizableviews you can use to CRUD application instances, just point your browser at:

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:

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

Theuser_name andpassword are the credential of the users registered in yourAuthorization Server, like any user created in Step 2.Response should be something like:

{"access_token":"<your_access_token>","token_type":"Bearer","expires_in":36000,"refresh_token":"<your_refresh_token>","scope":"read write groups"}

Grab your access_token and start using your new OAuth2 API:

# Retrieve userscurl-H"Authorization: Bearer <your_access_token>"http://localhost:8000/users/curl-H"Authorization: Bearer <your_access_token>"http://localhost:8000/users/1/# Retrieve groupscurl-H"Authorization: Bearer <your_access_token>"http://localhost:8000/groups/# Insert a new usercurl-H"Authorization: Bearer <your_access_token>"-XPOST-d"username=foo&password=bar&scope=write"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 therefresh token:

curl-XPOST-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 firstaccess_token request, containing a new access_token and refresh_token:

{"access_token":"<your_new_access_token>","token_type":"Bearer","expires_in":36000,"refresh_token":"<your_new_refresh_token>","scope":"read write groups"}

Step 5: Testing Restricted Access

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

curl-XPOST-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 isread:

{"access_token":"<your_access_token>","token_type":"Bearer","expires_in":36000,"refresh_token":"<your_refresh_token>","scope":"read"}

We now try to access our resources:

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

OK, this one works since users read only requiresread scope.

# 'groups' scope neededcurl-H"Authorization: Bearer <your_access_token>"http://localhost:8000/groups/# 'write' scope neededcurl-H"Authorization: Bearer <your_access_token>"-XPOST-d"username=foo&password=bar"http://localhost:8000/users/

You’ll get a"Youdonothavepermissiontoperformthisaction" error because your access_token does not provide therequired scopesgroups andwrite.