Skip to main content

Django JWT Auth Middlware

Installation

  1. Add the configuration for django_jwt_auth_middleware to your settings as follows:
INSTALLED_APPS = [
    # ...,
    "django_jwt_auth_middlware",
    # ...,
]

# ...

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",  # default
    "django_jwt_auth_middleware.auth.JWTAuthenticationBackend",
]

# ...

# the middleware must go after django's SecurityMiddleware, SessionMiddleware,
# and AuthenticationMiddleware. Putting it at the end is always safe.
MIDDLEWARE = [
    # ...,
    "django_jwt_auth_middleware.auth.JWTAuthenticationMiddleware",
]
  1. If you wish to use the default URL paths (/jwt/...), then in urls.py, make the changes below. Alternatively, you can import the views Login, Logout, and Refresh views (class-based) directly and attach URL patterns to them however you wish. NOTE: the default paths do not have URL names specified for referencing.
# using default paths
from django_jwt_auth_middleware.urls import urlpatterns as jwt_auth_patterns
from django.urls import path, include

urlpatterns = [
    # ...,
    path('', include(jwt_auth_patterns))
]

# using custom paths
from django_jwt_auth_middleware.views import Login, Logout, Refresh

urlpatterns = [
    # ...,
    path('login/', Login.as_view(), name='login'),
    path('logout/', Logout.as_view(), name='logout'),
    path('refresh/', Refresh.as_view(), name='refresh'),
]

You're now ready to start authenticating!

Usage

This section assumes you have at least one user defined for your application.

Login

In order to log in, send a POST request to the associated view (default: /jwt/login/) with the POST body specifying two keys: username, and password. If the username and password authenticate successfully, then a token will be issued and stored in the client's browser containing the value Bearer <tok> and a 200 is returned, where <tok> here is the JWT that corresponds to the newly authenticated user. If the provided credentials do not match, a 400 is returned. The cookie name/header value that is used for the JWT corresponds to the JWT_ACCESS_HEADER setting (default: Authorization).

Refresh

This package is intended to implement best practices for JWT authentication and this includes utilizing two separate tokens, refresh and access, which are both issued during login. The access token is sent on every request and lasts only a short time and is used to identify the client to the server. The refresh token is sent only occasionally to acquire a new access token.

In order to refresh the access token, send a POST request to the associated view (default: /jwt/refresh/) with an empty POST body. As long as a valid refresh token exists in the browser, a new access token will be generated and stored securely in the browser. If a token is generated, a 200 is returned, otherwise a 403 is returned.

Logout

When utilizing JWT authentication, logout is functionally identically to forgetting the refresh token (and potentially also the access token, but that will expire shortly anyway so the necessity of this depends on your threat model). By default the logout functionality removes both the access and refresh tokens. To perform the logout, simply send a POST request to the associated view (default: /jwt/logout/) with an empty POST body. As long as a valid access token exists in the browser, the client will be logged out. If the log out is successful, a 200 is returned, otherwise a 401 is returned.

Configuration

A list of Django settings are provided here that describes the configuration options for this package.

SETTING DEFAULT DESCRIPTION
JWT_ACCESS_DURATION 5 The duration in minutes that access tokens should remain valid after they are issued.
JWT_ACCESS_HEADER "Authorization" The name of the header that should be used for storing the access token. NOTE: If referencing this value within request.META, the header is prefixed with HTTP_ and is in all caps (e.g. HTTP_AUTHORIZATION)
JWT_ALGORITHM "HS256" The algorithm to use for signing the JWTs.
JWT_COOKIE_HTTPONLY True Whether or not the httponly attribute should be set on the cookies stored in the browser. NOTE: if testing with Postman, disable this value in development or this package won't function correctly.
JWT_COOKIE_SAMESITE "Strict" What the samesite attribute of the cookies should be set to. Options are "Strict" or "Lax".
JWT_COOKIE_SECURE True Whether or not the secure attribute should be set on the cookies stored in the browser. NOTE: if testing with Postman, disable this value in development or this package won't function correctly.
JWT_LOGOUT_ACCESS True Whether or not to remove the access token when logging out. If this is set to False, only the refresh token is removed and user access will continue until the access token expires.
JWT_REFRESH_DURATION 14 The duration in days that refresh tokens should remain valid after they are issued.
JWT_REFRESH_PATH "/jwt/refresh/" The path attribute that is set on the refresh token cookies. The controls when the cookies is sent. If the path is not a prefix of the current request, the browser won't send the token. This helps prevent the refresh token from being leaked.

Metadata

Release files for django-jwt-auth-middleware 0.1.1

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

Source distribution (sdist)

Source distribution for django-jwt-auth-middleware 0.1.1
File Size Uploaded Provenance
django-jwt-auth-middleware-0.1.1.tar.gz 10.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-jwt-auth-middleware 0.1.1
File Interpreter ABI Platform
django_jwt_auth_middleware-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 19.7 kB

Release files / django-jwt-auth-middleware-0.1.1.tar.gz

Download URL django-jwt-auth-middleware-0.1.1.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
0553a7b23fa4429c22d575606a00201a27cefcd4b6f4cad2658ecee925ddcbd6
BLAKE2b-256 checksum
How to use checksums
9006427968cc799da7697d2162f23133cb45bcaf1b5a6d86450473d03a24bd93
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.5

Release files / django_jwt_auth_middleware-0.1.1-py3-none-any.whl

Download URL django_jwt_auth_middleware-0.1.1-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c4ce4ca34048ceebc576804d1ec124225483ff9e456cbb6bcf38eff51cf7ee40
BLAKE2b-256 checksum
How to use checksums
66f8ba1907418689feb913886cef9cbfb1e896de6e384541d41b5abed21a4acb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.5

Security for django-jwt-auth-middleware 0.1.1

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.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

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