Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

permissions - 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?

question from:https://stackoverflow.com/questions/65892797/how-can-i-restrict-who-has-access-to-the-graphiql-api-browser-with-graphene-djan

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)),
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...