How to use Graphene GraphQL framework with Django REST Framework authentication
Asked Answered
T

2

23

I got some REST API endpoints in Django and I'd like to use the same authentication for Graphene. The documentation does not provide any guidance.

Trantrance answered 18/8, 2016 at 20:19 Comment(0)
T
23

For example, if you are using authentication_classes = (TokenAuthentication,) in your API views, you could add an endpoint to a GraphQLView decorated in this way:

urls.py:

# ...
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes, permission_classes, api_view

def graphql_token_view():
    view = GraphQLView.as_view(schema=schema)
    view = permission_classes((IsAuthenticated,))(view)
    view = authentication_classes((TokenAuthentication,))(view)
    view = api_view(['GET', 'POST'])(view)
    return view

urlpatterns = [
# ...
    url(r'^graphql_token', graphql_token_view()),
    url(r'^graphql', csrf_exempt(GraphQLView.as_view(schema=schema))),
    url(r'^graphiql', include('django_graphiql.urls')),
# ...

Note that we added a new ^graphql_token endpoint and kept the original ^graphql which is used by the GraphiQL tool.

Then, you should set the Authorization header in your GraphQL client and point to the graphql_token endpoint.


UPDATE: See this GitHub issue where people have suggested alternative solutions and full working examples.

Trantrance answered 18/8, 2016 at 20:19 Comment(5)
Does this still work for you? I am trying to do the same with SessionAuthentication but I get an error back from graphene-django when it tries to read the body of the request?Melodrama
Still works, but I haven't the most up-to-date versions of packages. My answer used: Django==1.8.3 djangorestframework==3.2.2 django-graphiql==0.4.4 graphene==0.10.2 graphql-core==0.5.3 graphql-django-view==1.3 graphql-relay==0.4.4Trantrance
is it possible to do a post request ?Victual
@KentDelaCruzFueconcillo Yes.Trantrance
Can you further explain what this means? Note that we added a new ^graphql_token endpoint and kept the original ^graphql which is used by the GraphiQL tool. Why do you have 2 seperate endpoints?Xenon
L
3

Adding some additional steps that I had to take when following this integration:

class RTGraphQLView(GraphQLView):

def parse_body(self, request):
    if type(request) is rest_framework.request.Request:
        return request.data
    return super().parse_body(request)

Graphene was expecting the .body attr but DRF reads it and attaches it to .data before being passed to GraphQLView.

Lovelorn answered 1/2, 2017 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.