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

标签 python django oauth-2.0 django-rest-framework oauth2-toolkit

我正在使用 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()

关于python - 每个特定方法的 Django OAuth 工具包范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307998/

相关文章:

python - 带有 postgresql 的 Django - manage.py syncdb 返回错误

java - 如何实现谷歌OAuth?

c# - 迁移到 OAuth 2.0 后获取 access_token 时出现问题

python - 使用 wxPython 返回多个文件路径以在另一个函数中使用

python - 使用 Python 正则表达式验证日期格式

Python:内存中字符串的大小

不应用 CSS 规则

python - Django 休息框架外键约束无法创建模型

android - API Callback_URL 无效调用

python - Python 中的递归函数不返回任何值