JSON Web Token for Django GraphQL
Project description
JSON Web Token authentication for Django GraphQL
Dependencies
Django ≥ 1.11
Installation
Install last stable version from Pypi.
pip install django-graphql-jwt
Include the JSONWebTokenMiddleware middleware in your MIDDLEWARE settings:
MIDDLEWARE = [
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'graphql_jwt.middleware.JSONWebTokenMiddleware',
...
]
Include the JSONWebTokenBackend backend in your AUTHENTICATION_BACKENDS settings:
AUTHENTICATION_BACKENDS = [
'graphql_jwt.backends.JSONWebTokenBackend',
'django.contrib.auth.backends.ModelBackend',
]
Schema
Add mutations to the root schema.
import graphene
import graphql_jwt
class Mutations(graphene.ObjectType):
token_auth = graphql_jwt.ObtainJSONWebToken.Field()
verify_token = graphql_jwt.Verify.Field()
refresh_token = graphql_jwt.Refresh.Field()
schema = graphene.Schema(mutations=Mutations)
tokenAuth to authenticate the user and obtain the 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
}
}
verifyToken to confirm that the token is valid.
mutation VerifyToken($token: String!) {
verifyToken(token: $token) {
payload
}
}
refreshToken to obtain a brand new token with renewed expiration time for non-expired tokens.
[wiki] Configure your refresh token scenario and set the flag JWT_VERIFY_EXPIRATION=true.
mutation RefreshToken($token: String!) {
refreshToken(token: $token) {
token
payload
}
}
Authentication in GraphQL queries
Now in order to access protected API you must include the Authorization: JWT <token> header.
Django-graphql-jwt uses middleware to hook the authenticated user into request object. The simple, raw way to limit access to data is to check info.context.user.is_authenticated:
import graphene
class Query(graphene.ObjectType):
viewer = graphene.Field(UserType)
def resolve_viewer(self, info, **kwargs):
user = info.context.user
if not user.is_authenticated:
raise Exception('Authentication credentials were not provided')
return user
[wiki] As a shortcut, you can use a login_required() decorator for your queries and mutations:
import graphene
class Query(graphene.ObjectType):
viewer = graphene.Field(UserType)
@login_required
def resolve_viewer(self, info, **kwargs):
return info.context.user
Relay
Complete support for Relay.
import graphene
import graphql_jwt
class Mutations(graphene.ObjectType):
token_auth = graphql_jwt.relay.ObtainJSONWebToken.Field()
verify_token = graphql_jwt.relay.Verify.Field()
refresh_token = graphql_jwt.relay.Refresh.Field()
Customizing
If you want to customize the ObtainJSONWebToken behavior, you’ll need to customize the .resolve() method on a subclass of JSONWebTokenMutation or .relay.JSONWebTokenMutation.
import graphene
import graphql_jwt
class ObtainJSONWebToken(graphql_jwt.JSONWebTokenMutation):
user = graphene.Field(UserType)
@classmethod
def resolve(cls, root, info):
return cls(user=info.context.user)
Authenticate the user and obtain the token and the user id.
mutation TokenAuth($username: String!, $password: String!) {
tokenAuth(username: $username, password: $password) {
token
user {
id
}
}
}
Environment variables
Algorithm for cryptographic signing Default: HS256
Identifies the recipients that the JWT is intended for Default: None
Identifies the principal that issued the JWT Default: None
Validate an expiration time which is in the past but not very far Default: seconds=0
The secret key used to sign the JWT Default: settings.SECRET_KEY
Secret key verification Default: True
Expiration time verification Default: False
JWT_EXPIRATION_DELTA
Timedelta added to utcnow() to set the expiration time Default: minutes=5
JWT_ALLOW_REFRESH
Enable token refresh Default: True
JWT_REFRESH_EXPIRATION_DELTA
Limit on token refresh Default: days=7
JWT_AUTH_HEADER_PREFIX
Authorization prefix Default: JWT
Credits to @jpadilla / django-rest-framework-jwt.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django-graphql-jwt-0.1.7.tar.gz.
File metadata
- Download URL: django-graphql-jwt-0.1.7.tar.gz
- Upload date:
- Size: 11.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
02382f5a3bc1678eb5c6642c33b31bc1548d0fb643f5b45be499302494e7eabf
|
|
| MD5 |
132156e995e81c823a2e71dd79d7cd68
|
|
| BLAKE2b-256 |
8f06785b5db61f10632b8a7dcfe0c24239da1895c90bc69769891486404899c4
|
File details
Details for the file django_graphql_jwt-0.1.7-py2.py3-none-any.whl.
File metadata
- Download URL: django_graphql_jwt-0.1.7-py2.py3-none-any.whl
- Upload date:
- Size: 15.0 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
89bb6bd5baed00236d2c24bcb464621484c07ce992f6999dbd5d3e282f7cfe7a
|
|
| MD5 |
4a76b07424508a4eb076bc4c88cb6e5e
|
|
| BLAKE2b-256 |
10f98a797297df4928eb25e3e26020cd6d6730187fcc35b2c75adb7b554d9f4c
|