Skip to main content

Django middleware for utilizing JWT for authentication.

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-jwt-auth-middleware-0.1.1.tar.gz (10.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_jwt_auth_middleware-0.1.1-py3-none-any.whl (9.2 kB view details)

Uploaded Python 3

File details

Details for the file django-jwt-auth-middleware-0.1.1.tar.gz.

File metadata

File hashes

Hashes for django-jwt-auth-middleware-0.1.1.tar.gz
Algorithm Hash digest
SHA256 0553a7b23fa4429c22d575606a00201a27cefcd4b6f4cad2658ecee925ddcbd6
MD5 a2f388d59d6fb2e2ed71067b2c49ea9a
BLAKE2b-256 9006427968cc799da7697d2162f23133cb45bcaf1b5a6d86450473d03a24bd93

See more details on using hashes here.

File details

Details for the file django_jwt_auth_middleware-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_jwt_auth_middleware-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c4ce4ca34048ceebc576804d1ec124225483ff9e456cbb6bcf38eff51cf7ee40
MD5 6c4a81b13fee93cb517c2ff5306781c9
BLAKE2b-256 66f8ba1907418689feb913886cef9cbfb1e896de6e384541d41b5abed21a4acb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page