Django OAuthToolkit每个特定方法的范围

时间:2017-11-15 12:54:58

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

我正在使用Django Rest Framework和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方法应该有不同的范围。如何为不同的方法设置不同的范围?

2 个答案:

答案 0 :(得分:1)

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

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)

并在您的视图中使用它:

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

答案 1 :(得分:1)

也许您可以使用TokenMatchesOASRequirements权限类

class SongView(views.APIView):
    authentication_classes = [OAuth2Authentication]
    permission_classes = [TokenMatchesOASRequirements]
    required_alternate_scopes = {
        "GET": [["read"]],
        "POST": [["create"], ["post", "widget"]],
        "PUT":  [["update"], ["put", "widget"]],
        "DELETE": [["delete"], ["scope2", "scope3"]],
    }