3

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
Moritz
  • 2,987
  • 3
  • 21
  • 34
  • 1
    *"... but not for use as an API."* I don't understand this, Can you elaborate? What kind of security do you wish to add to the GrpphQL views? – JPG Oct 05 '20 at 13:08
  • Basically, is the implementation above safe against CSRF? Otherwise, what is a safe method of securing a POST endpoint without having to use CSRF protection? – Moritz Oct 05 '20 at 15:27
  • Can I ask whats wrong with csrf? @Moritz – JPG Oct 05 '20 at 15:28
  • How can a valid CSRF token be obtained without a logged in session, but with a token authentication? From experience with other APIs only the token is required for authentication, not fetching a CSRF token and then submitting it with the POST request. – Moritz Oct 05 '20 at 15:31

0 Answers0