flavors / django-graphql-jwt

JSON Web Token (JWT) authentication for Graphene Django

Home Page:https://django-graphql-jwt.domake.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

request.user in classical django views always AnonymousUser

merodrem opened this issue · comments

Hello everyone,

I have an application working mainly with graphql, but I also have some "classical" django views to download files. graphql_jwt works great with graphql queries and mutations, but in an http view, the request.user is always AnonymousUser.
This is how I defined my middlewares and authentication backends:
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]

GRAPHENE = { 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], }

AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'graphql_jwt.backends.JSONWebTokenBackend', ]

I tried using the from graphql_jwt.decorators.login_required decorator on my http views, but the decorator crashes.

Is it a normal behaviour? Shouldn't the request know the user is logged in if there's a token with the request (stored in a cookie in my case )?

Have a good day :-)

Hi fellows,

I'm not sure of myself because I feel like I'm duplicating auth mecanisms, but I found a workaround. Just override the ObtainJSONWebToken mutation to include django's login method:

class ObtainJSONWebToken(graphql_jwt.JSONWebTokenMutation):
    user = graphene.Field(ProfileType)

    @classmethod
    def resolve(cls, root, info, **kwargs):
        login(info.context, info.context.user)
        return cls(user=info.context.user)

Similarly, you can consider a logout mutation to call along with deleteToken:

class LogoutMutation(graphene.Mutation):
    status = graphene.Field(graphene.String)

    @classmethod
    def mutate(cls, root, info, **kwargs):
        logout(info.context)
        return LogoutMutation(status='OK')
commented

Hey @merodrem ,
that is the expected behavior, Django middleware was removed in favor of Graphene middleware: PR 125
If you want to extend authentication system to Django views, you can recover this old middleware and add it to your project.