Graphene provides a GraphQL integration into Django and supplies a view to create a URL endpoint. The question is how can the endpoint be protected for API usage? The recommend method is to use a LoginRequiredMixin which is great for logged in users, but not for use as an API.
I've tried integrating it with DRF tokens, but still end up with the session middleware requiring CSRF. The only solution that works is adding a CSRF exempt decorator, but I fear that this opens up a security vulnerability.
# urls.py
path("graphiql/", root_views.SessionGraphQLView.as_view(graphiql=True), name="graphiql"),
path("graphql/", root_views.TokenGraphQLView.as_view(graphiql=False), name="graphql"),
# views.py
class TokenLoginRequiredMixin(AccessMixin):
"""A login required mixin that allows token authentication."""
def dispatch(self, request, *args, **kwargs):
"""If token was provided, ignore authenticated status."""
http_auth = request.META.get("HTTP_AUTHORIZATION")
if http_auth and "Token" in http_auth:
pass
elif not request.user.is_authenticated:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
@method_decorator(csrf_exempt, name="dispatch")
class TokenGraphQLView(TokenLoginRequiredMixin, GraphQLView):
authentication_classes = [TokenAuthentication]
class SessionGraphQLView(LoginRequiredMixin, GraphQLView):
pass