Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Strawberry Django JWT

PyPI - Downloads GitHub commit activity GitHub last commit

JSON Web Token authentication for Strawberry Django GraphQL


Disclaimer

This project is a forked version of Django GraphQL JWT that substitutes Graphene GraphQL backend for Strawberry


Installation

  1. Install last stable version from Pypi:

    pip install strawberry-django-jwt
    
  2. Add AuthenticationMiddleware middleware to your MIDDLEWARE settings:

    MIDDLEWARE = [
        ...,
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        ...,
    ]
    
  3. Add JSONWebTokenMiddleware or AsyncJSONWebTokenMiddleware middleware to your STRAWBERRY schema definition:

    from strawberry_django_jwt.middleware import JSONWebTokenMiddleware, AsyncJSONWebTokenMiddleware
    from strawberry import Schema
    
    schema = Schema(...)
    schema.middleware.extend([
         # !! IMPORTANT !!
         # Pick only one, async middleware is needed when using AsyncGraphQLSchema
         JSONWebTokenMiddleware(),
         AsyncJSONWebTokenMiddleware(),
    ])
    
  4. Add JSONWebTokenBackend backend to your AUTHENTICATION_BACKENDS:

    AUTHENTICATION_BACKENDS = [
        'strawberry_django_jwt.backends.JSONWebTokenBackend',
        'django.contrib.auth.backends.ModelBackend',
    ]
    
  5. Add strawberry-django-jwt mutations to the root schema:

    import strawberry
    import strawberry_django_jwt.mutations as jwt_mutations
    
    @strawberry.type
    class Mutation:
        token_auth = jwt_mutations.ObtainJSONWebToken.obtain
        verify_token = jwt_mutations.Verify.verify
        refresh_token = jwt_mutations.Refresh.refresh
        delete_token_cookie = jwt_mutations.DeleteJSONWebTokenCookie.delete_cookie
    
    
    schema = strawberry.Schema(mutation=Mutation, query=...)
    
  6. [OPTIONAL] Set up the custom Strawberry views

    These views set the status code of failed authentication attempts to 401 instead of the default 200.

    from django.urls import re_path
    from strawberry_django_jwt.decorators import jwt_cookie
    from strawberry_django_jwt.views import StatusHandlingGraphQLView as GQLView
    from ... import schema
    
    urlpatterns += \
     [
         re_path(r'^graphql/?$', jwt_cookie(GQLView.as_view(schema=schema))),
     ]
    

    or, for async views:

    from django.urls import re_path
    from strawberry_django_jwt.decorators import jwt_cookie
    from strawberry_django_jwt.views import AsyncStatusHandlingGraphQLView as AGQLView
    from ... import schema
    
    urlpatterns += \
     [
         re_path(r'^graphql/?$', jwt_cookie(AGQLView.as_view(schema=schema))),
     ]
    

Quickstart Documentation

===============Work in Progress===============

Relay support has been temporarily removed due to lack of experience with Relay

Most of the features are conceptually the same as those provided by Django GraphQL JWT

Authenticating fields

Fields can be set to auth-only using the login_required decorator in combination with strawberry.field or via login_field

import strawberry
from strawberry.types import Info
from strawberry_django_jwt.decorators import login_required


def auth_field(fn=None):
    return strawberry.field(login_required(fn))


@strawberry.type
class Query:
    @auth_field
    def hello(self, info: Info) -> str:
        return "World"

    @strawberry.field
    @login_required
    def foo(self, info: Info) -> str:
        return "Bar"

Please note the info argument, without which strawberry would not provide the context info required for authentication.

Mixin info injection

An alternative approach to this problem is following:

import strawberry
from strawberry.types import Info
from strawberry_django_jwt.decorators import login_required, login_field
from strawberry_django_jwt.mixins import RequestInfoMixin


@strawberry.type
class Query(RequestInfoMixin):
    @login_field
    def hello(self) -> str:
        # self == { 'info': ... } in this case
        return "World"

    @strawberry.field
    @login_required
    def foo(self) -> str:
        # self == { 'info': ... } in this case
        return self.get("info").field_name

    @strawberry.field
    @login_required
    def explicit_foo(self, info: Info) -> str:
        # self == { } in this case
        return info.field_name

RequestInfoMixin automatically injects info arguments to all fields in the class.

All function arguments that are not present in the definition will be added by the login_required decorator to the self dictionary as kwargs.

Async views

Should be fully supported :)

import strawberry
from strawberry_django_jwt.decorators import login_field
from strawberry_django_jwt.mixins import RequestInfoMixin


@strawberry.type
class Query(RequestInfoMixin):
    @login_field
    async def foo(self) -> str:
        return "bar"

Metadata

Release files for strawberry-django-jwt 0.1.1.dev1624312627

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for strawberry-django-jwt 0.1.1.dev1624312627
File Size Uploaded Provenance Actions
strawberry-django-jwt-0.1.1.dev1624312627.tar.gz 26.7 kB Without provenance Details for strawberry-django-jwt-0.1.1.dev1624312627.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for strawberry-django-jwt 0.1.1.dev1624312627
File Interpreter ABI Platform Actions
strawberry_django_jwt-0.1.1.dev1624312627-py3-none-any.whl Python 3 none any Details for strawberry_django_jwt-0.1.1.dev1624312627-py3-none-any.whl

Total release size: 74.3 kB

Release files / strawberry-django-jwt-0.1.1.dev1624312627.tar.gz

Download URL strawberry-django-jwt-0.1.1.dev1624312627.tar.gz
Size 26.7 kB
Tags Source
SHA-256 checksum
How to use checksums
88d79322dfde7594f11adc7028cee456d719c2dc158ad72a3e499074afec71ae
BLAKE2b-256 checksum
How to use checksums
d4779fb5acb14383719e25ae8b8430c6cd3ec072065f28b31365519510dde7c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.6 CPython/3.8.2 Linux/5.8.0-1033-azure

Release files / strawberry_django_jwt-0.1.1.dev1624312627-py3-none-any.whl

Download URL strawberry_django_jwt-0.1.1.dev1624312627-py3-none-any.whl
Size 47.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93d234cd93d9280fbc0b27bd3022959815d959c659cc83bf526a6e929fb65464
BLAKE2b-256 checksum
How to use checksums
86c0586f369e726ecd8ef8923a17a533bc3d124d90ccf6a36944bbfb174bcd6d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.6 CPython/3.8.2 Linux/5.8.0-1033-azure

Security for strawberry-django-jwt 0.1.1.dev1624312627

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page