question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

It does not support Django Rest Framework token authentication backend

See original GitHub issue

when I try to access info.context.user it all the time returns anonymous user, my same code works fine with django-graphql-jwt

Debugging gives me this :

-> return self.middleware
(Pdb) self.middleware
[<graphene_django.debug.middleware.DjangoDebugMiddleware object at 0x7fb93ac8d590>]
(Pdb)

Means that no auth middleware has been set to the graphql view

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5

github_iconTop GitHub Comments

16reactions
vinayan3commented, Aug 2, 2018

To support DRF Token Authentication Backend I wrote a class which derives from GraphQLVIew.

from django.http import HttpResponse
from graphene_django.views import GraphQLView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.permissions import IsAuthenticated
from rest_framework import status

class AuthenticatedGraphQLView(GraphQLView):
  authentication_classes = [TokenAuthentication]
  permission_classes = [IsAuthenticated]

  def authenticate_request(self, request):
    for auth_class in self.authentication_classes:
      auth_tuple = auth_class().authenticate(request)
      if auth_tuple:
        request.user, request.token = auth_tuple
        break

  def check_permissions(self, request):
    for permission_class in self.permission_classes:
      if not permission_class().has_permission(request, self):
        return False
    return True

  @method_decorator(csrf_exempt)
  def dispatch(self, request, *args, **kwargs):
    try:
      self.authenticate_request(request)
      has_permission = self.check_permissions(request)
      if not has_permission:
        return HttpResponse(
            json.dumps({'errors': ['permission denied']}),
            status=status.HTTP_403_FORBIDDEN,
            content_type='application/json')
    except AuthenticationFailed as auth_failed_error:
      return HttpResponse(
          json.dumps({
            'errors': [str(auth_failed_error)]
          }),
          status=status.HTTP_401_UNAUTHORIZED,
          content_type='application/json')
    return super(AuthenticatedGraphQLView, self).dispatch(request, *args, **kwargs)

(edit) added the imports

2reactions
danielmcquillencommented, Feb 25, 2020

@vinayan3 Thanks for posting your code!

Question…did you ever try adding SessionAuthentication to your authentication_classes ?

Doing so is helpful if you want logged in users to be able to access the GraphiQL UI. However, when I tried adjusting the code you posted like so:

authentication_classes = [TokenAuthentication, SessionAuthentication]

It fails when DRF tries looking for request._request as part of the sessions auth check.

'WSGIRequest' object has no attribute '_request'

Curious if anyone else has attempted to use DRF token authentication and session authentication such that the GraphiQL UI is available to logged in users.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Authentication - Django REST framework
This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable...
Read more >
Token authentication not working django rest framework
I am using token authentication for my current project but I have one problem, I can not authenticate a use for the life...
Read more >
Token Authentication for django-rest-framework - /var/
This means that if you have a server api.example.com that is used as a backend and a server www.example.com that will serve your...
Read more >
Django Rest Framework authentication: the easy way
Django Rest Framework authentication in your web application should be easy and secure. Forget JWT and use the good-old Django sessions in ...
Read more >
How to Implement Token Authentication using Django REST ...
In this tutorial you are going to learn how to implement Token-based authentication using Django REST Framework (DRF).
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found