Skip to content

Add Django 5.2 support to django-rest-framework-jwt #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions demo/app/migrations/0002_alter_userwithprofile_options_and_more.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 5.2.1 on 2025-05-09 08:56

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('app', '0001_initial'),
]

operations = [
migrations.AlterModelOptions(
name='userwithprofile',
options={'verbose_name': 'user', 'verbose_name_plural': 'users'},
),
migrations.AlterField(
model_name='userwithprofile',
name='first_name',
field=models.CharField(blank=True, max_length=150, verbose_name='first name'),
),
]
18 changes: 9 additions & 9 deletions demo/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@

from __future__ import unicode_literals

from django.urls import re_path, include
from rest_framework import routers

from rest_framework_jwt import views
from rest_framework_jwt.blacklist import views as blacklist_views
from rest_framework_jwt.compat import include, url

from .views import test_view, superuser_test_view, blacklist_test_view

router = routers.DefaultRouter()
router.register(r"blacklist", blacklist_views.BlacklistView, "blacklist")

urlpatterns = [
url(r"^auth/$", views.obtain_jwt_token, name="auth"),
url(r"^auth/verify/$", views.verify_jwt_token, name="auth-verify"),
url(r"^auth/refresh/$", views.refresh_jwt_token, name="auth-refresh"),
url(r"^impersonate/$", views.impersonate_jwt_token, name="impersonate"),
url(r"^test-view/$", test_view, name="test-view"),
url(r"^superuser-test-view/$", superuser_test_view, name="superuser-test-view"),
url(r"^blacklist-test-view/$", blacklist_test_view, name="blacklist-test-view"),
url(r"^", include(router.urls)),
re_path(r"^auth/$", views.obtain_jwt_token, name="auth"),
re_path(r"^auth/verify/$", views.verify_jwt_token, name="auth-verify"),
re_path(r"^auth/refresh/$", views.refresh_jwt_token, name="auth-refresh"),
re_path(r"^impersonate/$", views.impersonate_jwt_token, name="impersonate"),
re_path(r"^test-view/$", test_view, name="test-view"),
re_path(r"^superuser-test-view/$", superuser_test_view, name="superuser-test-view"),
re_path(r"^blacklist-test-view/$", blacklist_test_view, name="blacklist-test-view"),
re_path(r"^", include(router.urls)),
]
7 changes: 3 additions & 4 deletions demo/demo/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin

from rest_framework_jwt.compat import include, url
from django.urls import re_path, include


urlpatterns = [
url(r"^admin/", admin.site.urls),
url(r"^jwt/", include("app.urls")),
re_path(r"^admin/", admin.site.urls),
re_path(r"^jwt/", include("app.urls")),
]
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ Default is `False`.

## Extending/Overriding `JSONWebTokenAuthentication`

Right now `JSONWebTokenAuthentication` assumes that the JWT will come in the header, or a cookie if configured (see [JWT_AUTH_COOKIE](#JWT_AUTH_COOKIE)). The JWT spec does not require this (see: [Making a service Call](https://developer.atlassian.com/static/connect/docs/concepts/authentication.html)). For example, the JWT may come in the querystring. The ability to send the JWT in the querystring is needed in cases where the user cannot set the header (for example the src element in HTML).
Right now `JSONWebTokenAuthentication` assumes that the JWT will come in the header, or a cookie if configured (see [JWT_AUTH_COOKIE](#jwt_auth_cookie)). The JWT spec does not require this (see: [Making a service Call](https://developer.atlassian.com/static/connect/docs/concepts/authentication.html)). For example, the JWT may come in the querystring. The ability to send the JWT in the querystring is needed in cases where the user cannot set the header (for example the src element in HTML).

To achieve this functionality, the user might write a custom `Authentication` class:

Expand Down
3 changes: 3 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ site_description: JSON Web Token Authentication support for Django REST Framewor
site_dir: html
theme: readthedocs
repo_url: https://github.com/Styria-Digital/django-rest-framework-jwt
markdown_extensions:
- toc:
permalink: true
20 changes: 8 additions & 12 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ classifiers =
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.11
Programming Language :: Python :: 3.12
Topic :: Internet :: WWW/HTTP

[paths]
Expand All @@ -33,13 +30,13 @@ source =
.tox/*/lib/python*/site-packages/rest_framework_jwt

[options]
python_requires = >= 2.7, != 3.0.*, != 3.1.*, != 3.2.*, != 3.3.*, != 3.4.*
python_requires = >= 3.11
zip_safe = False
include_package_data = True
install_requires =
PyJWT[crypto]>=1.5.2,<3.0.0
Django>=1.11
djangorestframework>=3.7
PyJWT[crypto]>=2.0.0,<3.0.0
Django>=5.2
djangorestframework>=3.16,<3.17

[options.extras_require]
dev =
Expand All @@ -50,13 +47,12 @@ lint =
flake8
test =
mock
pytest>=3.0
pytest>=8.0
pytest-cov
pytest-django
pytest-runner
six
docs =
mkdocs==0.13.2
mkdocs==1.6.1

[bdist_wheel]
universal = 1
Expand Down
8 changes: 3 additions & 5 deletions src/rest_framework_jwt/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from django.apps import apps
from django.contrib.auth import get_user_model
from django.utils.encoding import force_str
from django.utils.encoding import force_str, smart_str
from django.utils.translation import gettext_lazy as _

from rest_framework import exceptions
from rest_framework.authentication import (
Expand All @@ -18,9 +19,6 @@
InvalidAuthorizationCredentials,
MissingToken,
)
from rest_framework_jwt.compat import gettext_lazy as _
from rest_framework_jwt.compat import smart_str
from rest_framework_jwt.compat import ExpiredSignature
from rest_framework_jwt.settings import api_settings


Expand Down Expand Up @@ -71,7 +69,7 @@ def authenticate(self, request):

try:
payload = self.jwt_decode_token(token)
except ExpiredSignature:
except jwt.ExpiredSignatureError:
msg = _('Token has expired.')
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
Expand Down
5 changes: 2 additions & 3 deletions src/rest_framework_jwt/blacklist/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-

from rest_framework.exceptions import AuthenticationFailed
from django.utils.translation import gettext_lazy as _

from rest_framework_jwt.compat import gettext_lazy as _
from rest_framework.exceptions import AuthenticationFailed


class MissingToken(AuthenticationFailed):
Expand All @@ -15,4 +15,3 @@ class InvalidAuthorizationCredentials(AuthenticationFailed):
status_code = 401
msg = _('Invalid Authorization header.')
default_code = 'invalid_authorization_credentials'

4 changes: 3 additions & 1 deletion src/rest_framework_jwt/blacklist/permissions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.utils.translation import gettext_lazy as _

from rest_framework.permissions import BasePermission

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.blacklist.models import BlacklistedToken
from rest_framework_jwt.compat import gettext_lazy as _, jwt_decode
from rest_framework_jwt.compat import jwt_decode

class IsNotBlacklisted(BasePermission):
message = _('You have been blacklisted.')
Expand Down
56 changes: 7 additions & 49 deletions src/rest_framework_jwt/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,74 +3,32 @@
from __future__ import unicode_literals

from datetime import datetime
import sys

from django import VERSION
import jwt

from .settings import api_settings


try:
from django.urls import include
except ImportError:
from django.conf.urls import include # noqa: F401


try:
from django.conf.urls import url
except ImportError:
from django.urls import re_path as url


if sys.version_info[0] == 2:
# Use unicode-aware gettext on Python 2
from django.utils.translation import ugettext_lazy as gettext_lazy
else:
from django.utils.translation import gettext_lazy as gettext_lazy


try:
from django.utils.encoding import smart_str
except ImportError:
from django.utils.encoding import smart_text as smart_str


def has_set_cookie_samesite():
return (VERSION >= (2,1,0))


def set_cookie_with_token(response, name, token):
params = {
'expires': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA,
'domain': api_settings.JWT_AUTH_COOKIE_DOMAIN,
'path': api_settings.JWT_AUTH_COOKIE_PATH,
'secure': api_settings.JWT_AUTH_COOKIE_SECURE,
'httponly': True
'httponly': True,
}

if has_set_cookie_samesite():
params.update({'samesite': api_settings.JWT_AUTH_COOKIE_SAMESITE})
params.update({'samesite': api_settings.JWT_AUTH_COOKIE_SAMESITE})

response.set_cookie(name, token, **params)


if jwt.__version__.startswith("2"):
jwt_version = 2
ExpiredSignature = jwt.ExpiredSignatureError
else:
jwt_version = 1
ExpiredSignature = jwt.ExpiredSignature

def jwt_decode(token, key, verify=None, **kwargs):
if verify is not None:
if jwt_version == 1:
kwargs["verify"] = verify
if "options" not in kwargs:
kwargs["options"] = {"verify_signature": verify}
else:
if "options" not in kwargs:
kwargs["options"] = {"verify_signature": verify}
else:
kwargs["options"]["verify_signature"] = verify
if jwt_version == 2 and "algorithms" not in kwargs:
kwargs["options"]["verify_signature"] = verify
if "algorithms" not in kwargs:
kwargs["algorithms"] = ["HS256"]
return jwt.decode(token, key, **kwargs)
return jwt.decode(token, key, **kwargs)
2 changes: 1 addition & 1 deletion src/rest_framework_jwt/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from __future__ import unicode_literals

from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext_lazy as _

from rest_framework import serializers

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.compat import gettext_lazy as _
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.utils import (
check_payload,
Expand Down
10 changes: 5 additions & 5 deletions src/rest_framework_jwt/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@

from django.apps import apps
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _

from rest_framework import serializers
from rest_framework.utils.encoders import JSONEncoder

from rest_framework_jwt.compat import gettext_lazy as _, jwt_version, jwt_decode, ExpiredSignature
from rest_framework_jwt.compat import jwt_decode
from rest_framework_jwt.settings import api_settings


Expand Down Expand Up @@ -127,15 +128,14 @@ def jwt_encode_payload(payload):
key = key[0]

enc = jwt.encode(payload, key, signing_algorithm, headers=headers, json_encoder=JSONEncoder)
if jwt_version == 1:
enc = enc.decode()

return enc


def jwt_decode_token(token):
"""Decode JWT token claims."""

if jwt_version == 2 and type(token) == bytes:
if type(token) == bytes:
token = token.decode()

options = {
Expand Down Expand Up @@ -211,7 +211,7 @@ def check_payload(token):

try:
payload = JSONWebTokenAuthentication.jwt_decode_token(token)
except ExpiredSignature:
except jwt.ExpiredSignatureError:
msg = _('Token has expired.')
raise serializers.ValidationError(msg)
except jwt.DecodeError:
Expand Down
13 changes: 7 additions & 6 deletions tests/models/test_blacklisted_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from datetime import datetime
from datetime import timedelta
from django.utils import timezone
from datetime import timezone
from django.utils import timezone as django_timezone

import pytest

Expand All @@ -21,7 +22,7 @@ def test_token_is_blocked_by_id(user, monkeypatch, id_setting):
payload = JSONWebTokenAuthentication.jwt_create_payload(user)
token = JSONWebTokenAuthentication.jwt_encode_payload(payload)

expiration = timezone.now() + timedelta(days=1)
expiration = django_timezone.now() + timedelta(days=1)
BlacklistedToken(
token_id=payload['jti'],
expires_at=expiration,
Expand All @@ -44,7 +45,7 @@ def test_refreshed_token_is_blocked_by_original_id(user, call_auth_refresh_endpo
refreshed_token = refresh_response.json()['token']
payload = JSONWebTokenAuthentication.jwt_decode_token(refreshed_token)

expiration = timezone.now() + timedelta(days=1)
expiration = django_timezone.now() + timedelta(days=1)
BlacklistedToken(
token_id=original_payload['jti'],
expires_at=expiration,
Expand All @@ -62,7 +63,7 @@ def test_token_is_blocked_by_value(user, monkeypatch, id_setting):
payload = JSONWebTokenAuthentication.jwt_create_payload(user)
token = JSONWebTokenAuthentication.jwt_encode_payload(payload)

expiration = timezone.now() + timedelta(days=1)
expiration = django_timezone.now() + timedelta(days=1)
BlacklistedToken(
token=token,
expires_at=expiration,
Expand All @@ -77,7 +78,7 @@ def test_token_is_not_blocked_by_value_when_ids_required(user, monkeypatch):
payload = JSONWebTokenAuthentication.jwt_create_payload(user)
token = JSONWebTokenAuthentication.jwt_encode_payload(payload)

expiration = timezone.now() + timedelta(days=1)
expiration = django_timezone.now() + timedelta(days=1)
BlacklistedToken(
token=token,
expires_at=expiration,
Expand All @@ -93,7 +94,7 @@ def test_token_is_not_blocked_by_id_when_ids_disabled(user, monkeypatch):
payload['jti'] = uuid.uuid4()
token = JSONWebTokenAuthentication.jwt_encode_payload(payload)

expiration = timezone.now() + timedelta(days=1)
expiration = django_timezone.now() + timedelta(days=1)
BlacklistedToken(
token_id=payload['jti'],
expires_at=expiration,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_management_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from django.conf import settings
from django.core.management import call_command
from six import StringIO
from io import StringIO
from pytest import raises
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

Expand Down
Loading