fromdjango.urlsimportpath,includefromdjango.contrib.auth.modelsimportUser,Groupfromdjango.contribimportadminadmin.autodiscover()fromrest_frameworkimportgenerics,permissions,serializersfromoauth2_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_provider.urls',namespace='oauth2_provider')),path('users/',UserList.as_view()),path('users/<pk>/',UserDetails.as_view()),path('groups/',GroupList.as_view()),# ...]

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.