Skip to content
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

Add support for using import strings with JWT_PUBLIC_KEY #286

Open
wants to merge 4 commits into
base: main
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ coverage.xml
dist/
docs/_build/
htmlcov/

.idea/
4 changes: 4 additions & 0 deletions graphql_jwt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"JWT_GET_REFRESH_TOKEN_HANDLER",
"JWT_ALLOW_ANY_HANDLER",
"JWT_ALLOW_ANY_CLASSES",
"JWT_PUBLIC_KEY",
)


Expand Down Expand Up @@ -103,6 +104,9 @@ def __getattr__(self, attr):
if attr in self.import_strings:
value = perform_import(value, attr)

if attr == "JWT_PUBLIC_KEY" and value is not None and callable(value):
value = value()

self._cached_attrs.add(attr)
setattr(self, attr, value)
return value
Expand Down
34 changes: 27 additions & 7 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
from .decorators import override_jwt_settings
from .testcases import TestCase

PRIVATE_KEY = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend(),
)


class JWTPayloadTests(TestCase):
@mock.patch(
Expand All @@ -35,20 +41,34 @@ def test_issuer(self):

class AsymmetricAlgorithmsTests(TestCase):
def test_rsa_jwt(self):
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend(),
)
public_key = private_key.public_key()
public_key = PRIVATE_KEY.public_key()
payload = utils.jwt_payload(self.user)

with override_jwt_settings(
JWT_PUBLIC_KEY=public_key,
JWT_PRIVATE_KEY=private_key,
JWT_PRIVATE_KEY=PRIVATE_KEY,
JWT_ALGORITHM="RS256",
):
token = utils.jwt_encode(payload)
decoded = utils.jwt_decode(token)

self.assertEqual(payload, decoded)


def get_rsa_jwt():
public_key = PRIVATE_KEY.public_key()
return public_key


class PublicKeyImportStringTest(TestCase):
def test_import_string_public_key(self):
payload = utils.jwt_payload(self.user)

with override_jwt_settings(
JWT_PRIVATE_KEY=PRIVATE_KEY,
JWT_PUBLIC_KEY="tests.test_utils.get_rsa_jwt",
JWT_ALGORITHM="RS256",
):
token = utils.jwt_encode(payload)
decoded = utils.jwt_decode(token)

Expand Down