Package: ariadne-jwt
Ariadne JWTJSON Web Token for Ariadne DjangoInstallationpipinstallariadne-jwtInclude theJSONWebTokenMiddlewarein yourMIDDLEWAREsettings:MIDDLEWARE=['django.contrib.auth.middleware.AuthenticationMiddleware','ariadne_jwt.middleware.JSONWebTokenMiddleware',]Include theJSONWebTokenBackendin yourAUTHENTICATION_BACKENDSsettings:AUTHENTICATION_BACKENDS=['ariadne_jwt.backends.JSONWebTokenBackend','django.contrib.auth.backends.ModelBackend']SchemaAdd mutations to your GraphQL schemaimportariadnefromariadne_jwtimportresolve_verify,resolve_refresh,resolve_token_auth,jwt_schema,GenericScalartype_defs='''type Mutation {...verifyToken(token: String!): VerifyTokenrefreshToken(token: String!): RefreshTokentokenAuth(username: String!, password:String!): TokenAuth...}'''mutation=ariadne.MutationType()mutation.set_field('verifyToken',resolve_verify)mutation.set_field('refreshToken',resolve_refresh)mutation.set_field('tokenAuth',resolve_token_auth)schema=ariadne.make_executable_schema([type_defs,jwt_schema],mutation,GenericScalar)tokenAuthto authenticate the user and obtain the JSON Web Token.The resolver uses User's modelUSERNAME_FIELD_, which by default isusername.mutationTokenAuth($username:String!,$password:String!){tokenAuth(username:$username,password:$password){token}}verifyTokento confirm that the token is valid.mutationVerifyToken($token:String!){verifyToken(token:$token){payload}}refreshTokento obtain a brand newtokenwith renewed expiration time for non-expired tokens.mutationRefreshToken($token:String!){refreshToken(token:$token){tokenpayload}}Authentication in GraphQL queriesNow in order to access protected API you must include theAuthorization: JWT <token>header. you can use
thelogin_required()decorator for yourresolvers:fromariadneimportQueryTypefromariadne_jwt.decoratorsimportlogin_requiredtype_defs='''type UserNode {username:Stringemail: String}type Query {me: UserNode}'''query=QueryType()@query.field('me')@login_requireddefresolve_viewer(self,info,**kwargs):returninfo.context.get('request').userCustomizingIf you want to customize thetokenAuthbehavior, you'll need to extend theTokenAuthtype and write a resolver
with @token_auth decorator.fromariadne_jwt.decoratorsimporttoken_authextended_type_defs='''type UserNode {idusernameemail}extend type TokenAuth {user: UserNode}'''@token_authdefresolve_token_auth(obj,info,**kwargs):return{'user':info.context.get('request').user}mutationTokenAuth($username:String!,$password:String!){tokenAuth(username:$username,password:$password){tokenuser{id}}}Settingsariadne-jwtreads your configuration from a singleDjango settingnamedGRAPHQL_JWTGRAPHQL_JWT={'JWT_VERIFY_EXPIRATION':True,'JWT_EXPIRATION_DELTA':timedelta(seconds=60*10)}Default SettingsDEFAULTS={# Algorithm for cryptographic signing'JWT_ALGORITHM':'HS256',# Identifies the recipients that the JWT is intended for'JWT_AUDIENCE':None,# Identifies the principal that issued the JWT'JWT_ISSUER':None,# Validate an expiration time which is in the past but not very far'JWT_LEEWAY':0,# The secret key used to sign the JWT'JWT_SECRET_KEY':settings.SECRET_KEY,# Secret key verification'JWT_VERIFY':True,# Expiration time verification'JWT_VERIFY_EXPIRATION':False,# Timedelta added to utcnow() to set the expiration time'JWT_EXPIRATION_DELTA':timedelta(seconds=60*5),# Enable token refresh'JWT_ALLOW_REFRESH':True,# Limit on token refresh'JWT_REFRESH_EXPIRATION_DELTA':timedelta(days=7),# Enable long time running refresh token'JWT_LONG_RUNNING_REFRESH_TOKEN':False,# The model to use to represent a refresh token'JWT_REFRESH_TOKEN_MODEL':'refresh_token.RefreshToken',# Refresh token number of bytes'JWT_REFRESH_TOKEN_N_BYTES':20,# Authorization header name'JWT_AUTH_HEADER':'HTTP_AUTHORIZATION',# Authorization prefix'JWT_AUTH_HEADER_PREFIX':'JWT',# A custom function *f(payload, context)* to encode the token'JWT_ENCODE_HANDLER':'ariadne_jwt.utils.jwt_encode',# A custom function *f(token, context)* to decode the token'JWT_DECODE_HANDLER':'ariadne_jwt.utils.jwt_decode',# A custom function *f(user, context)* to generate the token payload'JWT_PAYLOAD_HANDLER':'ariadne_jwt.utils.jwt_payload',# A custom function `f(payload)` to obtain the username'JWT_PAYLOAD_GET_USERNAME_HANDLER':(lambdapayload:payload.get(get_user_model().USERNAME_FIELD)),# A custom function `f(orig_iat, context)` to determine if refresh has expired'JWT_REFRESH_EXPIRED_HANDLER':'ariadne_jwt.utils.refresh_has_expired',}Writing testsfromdjango.contrib.authimportget_user_modelfromariadne_jwt.testcasesimportJSONWebTokenTestCaseclassUserTests(JSONWebTokenTestCase):defsetUp(self):self.user=get_user_model().objects.create_user(username='test',password='dolphins')self.client.authenticate(self.user)self.client.schema(type_defs,resolvers,directives=directives)deftest_get_user(self):query='''query GetUser($username: String) {user(username: $username) {id}}'''self.client.execute(query,variables={'username':self.user.username})Testing the libraryrun the following in root directorypythonrun_tests.py