每个特定方法的Django OAuthToolkit作用域

2024-10-01 00:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Django Rest框架和OAuthTookit。在

我希望令牌提供的作用域应该是特定于HTTP方法的。例如:-同一APIView的GET、PUT、DELETE应具有不同的作用域。在

以下是我的API。在

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

目前,作用域是在类级别设置的,这意味着要访问所有GET、PUT和DELETE方法,令牌应该有scope1。在

我希望不同的HTTP方法应该有不同的作用域。如何为不同的方法设置不同的范围?在


Tags: django方法框架restapihttpgetput
1条回答
网友
1楼 · 发布于 2024-10-01 00:34:34

为了处理这种情况,我认为您需要实现一个新的权限类,如下所示:

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)

在你的观点中这样使用它:

^{pr2}$

相关问题 更多 >