fromdjango.conf.urlsimporturl,includefromdjango.contrib.auth.modelsimportUser,Groupfromdjango.contribimportadminadmin.autodiscover()fromrest_frameworkimportpermissions,routers,serializers,viewsetsfromoauth2_provider.ext.rest_frameworkimportTokenHasReadWriteScope,TokenHasScope# first we define the serializersclassUserSerializer(serializers.ModelSerializer):classMeta:model=UserclassGroupSerializer(serializers.ModelSerializer):classMeta:model=Group# ViewSets define the view behavior.classUserViewSet(viewsets.ModelViewSet):permission_classes=[permissions.IsAuthenticated,TokenHasReadWriteScope]queryset=User.objects.all()serializer_class=UserSerializerclassGroupViewSet(viewsets.ModelViewSet):permission_classes=[permissions.IsAuthenticated,TokenHasScope]required_scopes=['groups']queryset=Group.objects.all()serializer_class=GroupSerializer# Routers provide an easy way of automatically determining the URL confrouter=routers.DefaultRouter()router.register(r'users',UserViewSet)router.register(r'groups',GroupViewSet)# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browseable API.urlpatterns=[url(r'^',include(router.urls)),url(r'^o/',include('oauth2_provider.urls',namespace='oauth2_provider')),url(r'^admin/',include(admin.site.urls)),]

Also add the following to your settings.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',)}

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