Search code examples
permissionsgraphene-pythongraphene-django

How can I restrict who has access to the GraphiQL API browser with graphene-django?


Graphene-Django docs note that you can pass graphiql=False when instantiating the GraphQLView if you do not want to use the GraphiQL API browser. However, I'd like to keep the GraphiQL API browser available, and merely restrict who has access to it. How can that be done?

For instance, how would I make it so that only "staff" users (who can access the Admin site) have permission to access the GraphiQL browser?


Solution

  • You can extend the Graphene-Django GraphQLView and override its can_display_graphiql method (defined here) to add this sort of logic.

    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)
    

    Then in your urls.py file, use your new GraphQLView instead of the default one:

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