Quickstart

Dependencies

  • Python ≥ 3.6

  • Django ≥ 2.0

Installation

Install last stable version v0.4.0 from Pypi:

pip install django-graphql-jwt

Add AuthenticationMiddleware middleware to your MIDDLEWARE settings:

MIDDLEWARE = [
    ...
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    ...
]

Add JSONWebTokenMiddleware middleware to your GRAPHENE settings:

GRAPHENE = {
    "SCHEMA": "mysite.myschema.schema",
    "MIDDLEWARE": [
        "graphql_jwt.middleware.JSONWebTokenMiddleware",
    ],
}

Add JSONWebTokenBackend backend to your AUTHENTICATION_BACKENDS:

AUTHENTICATION_BACKENDS = [
    "graphql_jwt.backends.JSONWebTokenBackend",
    "django.contrib.auth.backends.ModelBackend",
]

Schema

Add mutations to the root schema:

import graphene
import graphql_jwt


class Mutation(graphene.ObjectType):
    token_auth = graphql_jwt.ObtainJSONWebToken.Field()
    verify_token = graphql_jwt.Verify.Field()
    refresh_token = graphql_jwt.Refresh.Field()


schema = graphene.Schema(mutation=Mutation)

Queries

  • tokenAuth to authenticate the user and obtain a JSON Web Token.

    The mutation uses your User’s model USERNAME_FIELD, which by default is username:

    mutation TokenAuth($username: String!, $password: String!) {
      tokenAuth(username: $username, password: $password) {
        token
        payload
        refreshExpiresIn
      }
    }
    
  • verifyToken to validate the token and obtain the token payload:

    mutation VerifyToken($token: String!) {
      verifyToken(token: $token) {
        payload
      }
    }
    
  • refreshToken to obtain a brand new token with renewed expiration time:

    Configure your refresh token scenario and set to True the JWT_VERIFY_EXPIRATION setting.