Search code examples
pythondjangooauth-2.0django-rest-frameworkoauth2-toolkit

Django OAuthToolkit Scopes per specific method


I'm using Django Rest Framework and OAuthTookit.

I want that the scope provided by the token should be HTTP Method specific. For eg:- GET, PUT, DELETE of the same APIView should have different scopes.

Following are my APIs.

class MyView(RetrieveUpdateDestroyAPIView):
    permission_classes = [TokenHasScope]
    required_scopes = ['scope1']
    serializer_class = ModelSerializer
    queryset = Model.objects.all()

Currently, the scope is set at the class level, which means to access all the GET, PUT & DELETE method, the token should have scope1.

I want that there should be different scope for different HTTP methods. How can I set different scope for different methods?


Solution

  • To handle this case, I think you need to implement a new permission class, something like this:

    class TokenHasScopeForMethod(TokenHasScope):
    
         def has_permission(self, request, view):
             token = request.auth
    
             if not token:
                 return False
    
             if hasattr(token, "scope"):
                 # Get the scopes required for the current method from the view
                 required_scopes = view.required_scopes_per_method[request.method]
    
                 return token.is_valid(required_scopes)
    

    And use it in your view like this:

    class MyView(RetrieveUpdateDestroyAPIView):
         permission_classes = [TokenHasScopeForMethod]
         required_scopes_per_method = {'POST': ['post_scope'], 'GET': ['get_scope']}
         serializer_class = ModelSerializer
         queryset = Model.objects.all()