【问题标题】:How can I restrict who has access to the GraphiQL API browser with graphene-django?如何使用 graphene-django 限制谁可以访问 GraphiQL API 浏览器?
【发布时间】:2021-01-25 21:36:56
【问题描述】:

Graphene-Django docs 请注意,如果您不想使用 GraphiQL API 浏览器,则可以在实例化 GraphQLView 时传递 graphiql=False。但是,我想保持 GraphiQL API 浏览器可用,并且仅仅限制谁可以访问它。怎么可能?

例如,我将如何使只有“员工”用户(可以访问管理站点)有权访问 GraphiQL 浏览器?

【问题讨论】:

    标签: permissions graphene-python graphene-django


    【解决方案1】:

    您可以扩展 Graphene-Django GraphQLView 并覆盖其 can_display_graphiql 方法(定义为 here)以添加此类逻辑。

    from graphene_django.views import GraphQLView as BaseGraphQLView
    
    class GraphQLView(BaseGraphQLView):
        @classmethod
        def can_display_graphiql(cls, request, data):
            # Only allow staff users to access the GraphiQL interface
            if not request.user or not request.user.is_staff:
                return False
            return super().can_display_graphiql(request, data)
    

    然后在您的 urls.py 文件中,使用新的GraphQLView 而不是默认的:

    # import the GraphQLView defined above
    urlpatterns = [
        # ...
        path("graphql", GraphQLView.as_view(graphiql=True)),
    ]
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2015-03-15
      • 2020-11-02
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多