Getting started

    NOTE

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

    Create a virtualenv and install following packages using pip…

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

    1. 'django.contrib.admin',
    2. ...
    3. 'oauth2_provider',
    4. 'rest_framework',
    5. )

    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. }

    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 import User, 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 import TokenHasReadWriteScope, TokenHasScope
    7. # first we define the serializers
    8. class UserSerializer(serializers.ModelSerializer):
    9. class Meta:
    10. model = User
    11. fields = ('username', 'email', "first_name", "last_name")
    12. class GroupSerializer(serializers.ModelSerializer):
    13. class Meta:
    14. model = Group
    15. fields = ("name", )
    16. # Create the API views
    17. class UserList(generics.ListCreateAPIView):
    18. queryset = User.objects.all()
    19. serializer_class = UserSerializer
    20. class UserDetails(generics.RetrieveAPIView):
    21. permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    22. queryset = User.objects.all()
    23. serializer_class = UserSerializer
    24. class GroupList(generics.ListAPIView):
    25. permission_classes = [permissions.IsAuthenticated, TokenHasScope]
    26. required_scopes = ['groups']
    27. queryset = Group.objects.all()
    28. serializer_class = GroupSerializer
    29. # Setup the URLs and include login URLs for the browsable API.
    30. urlpatterns = [
    31. path('admin/', admin.site.urls),
    32. path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    33. path('users/', UserList.as_view()),
    34. path('users/<pk>/', UserDetails.as_view()),
    35. path('groups/', GroupList.as_view()),
    36. # ...
    37. ]

    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. )
    9. }

    Now run the following commands:

    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.

    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!

    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/
    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:

    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. }

    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:

    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

    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.