Skip to main content
 首页 » 编程设计

python之每个特定方法的 Django OAuth 工具包范围

2024年10月01日31lyhabc

我正在使用 Django Rest Framework 和 OAuthTookit .

我希望 token 提供的范围应该是特定于 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 方法, token 应该有 scope1。

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

请您参考如下方法:

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

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) 

然后像这样在你的 View 中使用它:

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