Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add iss to JWT tokens (#10842)

Maciej Korycinski2a59d31fc839
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84974c184c..8758981288 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add base shipping price to `Order` - #10771 by @fowczarek
- Add new field `audience` to App manifest. If provided, App's JWT access token will have `aud` field. - #10845 by @korycins
- GraphQL view no longer generates error logs when the HTTP request doesn't contain a GraphQL query - #10901 by @NyanKiyoshi
+- Add `iss` field to JWT tokens - #10842 by @korycins
### GraphQL API
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 98fbd78190..347768dcd2 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -30,7 +30,12 @@ def jwt_base_payload(
exp_delta: Optional[timedelta], token_owner: str
) -> Dict[str, Any]:
utc_now = datetime.utcnow()
- payload = {"iat": utc_now, JWT_OWNER_FIELD: token_owner}
+
+ payload = {
+ "iat": utc_now,
+ JWT_OWNER_FIELD: token_owner,
+ "iss": get_jwt_manager().get_issuer(),
+ }
if exp_delta:
payload["exp"] = utc_now + exp_delta
return payload
diff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.py
index c9dbc12269..916c24af3c 100644
--- a/saleor/core/jwt_manager.py
+++ b/saleor/core/jwt_manager.py
@@ -7,12 +7,16 @@ import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from django.conf import settings
+from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style
+from django.urls import reverse
from django.utils.module_loading import import_string
from jwt import api_jws
from jwt.algorithms import RSAAlgorithm
+from .utils import build_absolute_uri
+
logger = logging.getLogger(__name__)
PUBLIC_KEY: Optional[rsa.RSAPublicKey] = None
@@ -20,6 +24,10 @@ KID = "1"
class JWTManagerBase:
+ @classmethod
+ def get_domain(cls) -> str:
+ return NotImplemented
+
@classmethod
def get_private_key(cls) -> rsa.RSAPrivateKey:
return NotImplemented
@@ -50,10 +58,18 @@ class JWTManagerBase:
def get_jwks(cls) -> dict:
return NotImplemented
+ @classmethod
+ def get_issuer(cls) -> str:
+ return NotImplemented
+
class JWTManager(JWTManagerBase):
KEY_FILE_FOR_DEBUG = ".jwt_key.pem"
+ @classmethod
+ def get_domain(cls) -> str:
+ return Site.objects.get_current().domain
+
@classmethod
def get_private_key(cls) -> rsa.RSAPrivateKey:
pem = settings.RSA_PRIVATE_KEY
@@ -174,6 +190,10 @@ class JWTManager(JWTManagerBase):
except Exception as e:
raise ImproperlyConfigured(f"Unable to load provided PEM private key. {e}")
+ @classmethod
+ def get_issuer(cls) -> str:
+ return build_absolute_uri(reverse("api"), domain=cls.get_domain())
+
def get_jwt_manager() -> JWTManagerBase:
return import_string(settings.JWT_MANAGER_PATH)
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index e9515fe74a..23d55f9974 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -223,6 +223,18 @@ def test_build_absolute_uri(site_settings, settings):
assert logo_url == logo_location
+def test_build_absolute_uri_with_host(site_settings, settings):
+ # given
+ host = "test.com"
+ location = "images/close.svg"
+
+ # when
+ url = build_absolute_uri(location, host)
+
+ # then
+ assert url == f"http://{host}/{location}"
+
+
def test_delete_sort_order_with_null_value(menu_item):
"""Ensures there is no error when trying to delete a sortable item,
which triggers a shifting of the sort orders--which can be null."""
diff --git a/saleor/core/tests/test_jwt.py b/saleor/core/tests/test_jwt.py
index 68dea816ba..bafc1c03d7 100644
--- a/saleor/core/tests/test_jwt.py
+++ b/saleor/core/tests/test_jwt.py
@@ -1,9 +1,11 @@
import graphene
import jwt
from cryptography.hazmat.primitives import serialization
+from django.urls import reverse
from ...tests.consts import TEST_SERVER_DOMAIN
from ..jwt import create_access_token_for_app_extension, jwt_decode, jwt_encode
+from ..utils import build_absolute_uri
def test_create_access_token_for_app_extension_staff_user_with_more_permissions(
@@ -44,6 +46,7 @@ def test_create_access_token_for_app_extension_staff_user_with_more_permissions(
)
assert int(decode_extension_id) == extension.id
assert decoded_token["aud"] == audience
+ assert decoded_token["iss"] == build_absolute_uri(reverse("api"))
def test_create_access_token_for_app_extension_with_more_permissions(
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index e048e16c5b..19fb10d989 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -22,13 +22,13 @@ if TYPE_CHECKING:
from django.utils.safestring import SafeText
-def build_absolute_uri(location: str) -> Optional[str]:
+def build_absolute_uri(location: str, domain: Optional[str] = None) -> str:
"""Create absolute uri from location.
If provided location is absolute uri by itself, it returns unchanged value,
otherwise if provided location is relative, absolute uri is built and returned.
"""
- host = Site.objects.get_current().domain
+ host = domain or Site.objects.get_current().domain
protocol = "https" if settings.ENABLE_SSL else "http"
current_uri = "%s://%s" % (protocol, host)
location = urljoin(current_uri, location)
diff --git a/saleor/graphql/account/tests/mutations/test_token_create.py b/saleor/graphql/account/tests/mutations/test_token_create.py
index d469383d47..784a560aa7 100644
--- a/saleor/graphql/account/tests/mutations/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/test_token_create.py
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta, timezone
import graphene
+from django.urls import reverse
from freezegun import freeze_time
from .....account.error_codes import AccountErrorCode
@@ -10,6 +11,7 @@ from .....core.jwt import (
create_refresh_token,
jwt_decode,
)
+from .....core.utils import build_absolute_uri
from ....tests.utils import get_graphql_content
from ...mutations.authentication import _get_new_csrf_token
@@ -66,6 +68,7 @@ def test_create_token(api_client, customer_user, settings):
assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
+ assert payload["iss"] == build_absolute_uri(reverse("api"))
@freeze_time("2020-03-18 12:00:00")
@@ -217,3 +220,4 @@ def test_create_token_active_user_logged_before(api_client, customer_user, setti
assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
+ assert payload["iss"] == build_absolute_uri(reverse("api"))
diff --git a/saleor/graphql/account/tests/mutations/test_token_refresh.py b/saleor/graphql/account/tests/mutations/test_token_refresh.py
index f63cc18254..3e52d6bb9e 100644
--- a/saleor/graphql/account/tests/mutations/test_token_refresh.py
+++ b/saleor/graphql/account/tests/mutations/test_token_refresh.py
@@ -1,5 +1,6 @@
from datetime import datetime
+from django.urls import reverse
from freezegun import freeze_time
from .....account.error_codes import AccountErrorCode
@@ -11,6 +12,7 @@ from .....core.jwt import (
create_refresh_token,
jwt_decode,
)
+from .....core.utils import build_absolute_uri
from ....tests.utils import get_graphql_content
from ...mutations.authentication import _get_new_csrf_token
@@ -83,6 +85,7 @@ def test_refresh_token_get_token_from_cookie(api_client, customer_user, settings
)
assert payload["type"] == JWT_ACCESS_TYPE
assert payload["token"] == customer_user.jwt_token_key
+ assert payload["iss"] == build_absolute_uri(reverse("api"))
@freeze_time("2020-03-18 12:00:00")
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index 4f0ed1aa3e..a5115c65aa 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, patch
import graphene
import pytest
import pytz
+from django.contrib.sites.models import Site
from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import Money
@@ -769,6 +770,7 @@ def test_checkout_complete_requires_confirmation(
):
site_settings.automatically_confirm_all_new_orders = False
site_settings.save()
+ Site.objects.clear_cache()
payment = payment_dummy
payment.checkout = checkout_ready_to_complete
payment.save()
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 65d345bca8..5fd83328cd 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -8,6 +8,7 @@ import before_after
import graphene
import pytest
import pytz
+from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import transaction
@@ -937,6 +938,7 @@ def test_product_query_by_id_weight_returned_in_default_unit(
site_settings.default_weight_unit = WeightUnits.LB
site_settings.save(update_fields=["default_weight_unit"])
+ Site.objects.clear_cache()
variables = {
"id": graphene.Node.to_global_id("Product", product.pk),
@@ -4531,6 +4533,7 @@ def test_product_type_query_by_id_weight_returned_in_default_unit(
site_settings.default_weight_unit = WeightUnits.OZ
site_settings.save(update_fields=["default_weight_unit"])
+ Site.objects.clear_cache()
variables = {"id": graphene.Node.to_global_id("ProductType", product_type.pk)}
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index efd15ff735..afbdf76030 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -6,6 +6,7 @@ from uuid import uuid4
import graphene
import pytest
import pytz
+from django.contrib.sites.models import Site
from django.utils.text import slugify
from freezegun import freeze_time
from measurement.measures import Weight
@@ -98,6 +99,7 @@ def test_fetch_variant(
product,
permission_manage_products,
site_settings,
+ settings,
channel_USD,
):
# given
@@ -108,6 +110,7 @@ def test_fetch_variant(
site_settings.default_weight_unit = WeightUnits.G
site_settings.save(update_fields=["default_weight_unit"])
+ Site.objects.clear_cache()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
variables = {"id": variant_id, "countryCode": "EU", "channel": channel_USD.slug}
@@ -154,6 +157,7 @@ def test_fetch_variant_no_stocks(
site_settings.default_weight_unit = WeightUnits.G
site_settings.save(update_fields=["default_weight_unit"])
+ Site.objects.clear_cache()
warehouse = variant.stocks.first().warehouse
# remove the warehouse channels
diff --git a/saleor/graphql/shipping/tests/test_shipping_zones_query.py b/saleor/graphql/shipping/tests/test_shipping_zones_query.py
index b09c5ce0ff..ca852fcad0 100644
--- a/saleor/graphql/shipping/tests/test_shipping_zones_query.py
+++ b/saleor/graphql/shipping/tests/test_shipping_zones_query.py
@@ -1,5 +1,6 @@
import graphene
import pytest
+from django.contrib.sites.models import Site
from measurement.measures import Weight
from ....core.units import WeightUnits
@@ -96,6 +97,7 @@ def test_shipping_zone_query_weights_returned_in_default_unit(
site_settings.default_weight_unit = WeightUnits.G
site_settings.save(update_fields=["default_weight_unit"])
+ Site.objects.clear_cache()
query = SHIPPING_ZONE_QUERY
ID = graphene.Node.to_global_id("ShippingZone", shipping.id)
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index 7f2cfd2e44..13a88caee0 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -680,6 +680,7 @@ def test_shop_customer_set_password_url_update(
content = get_graphql_content(response)
data = content["data"]["shopSettingsUpdate"]
assert not data["errors"]
+ Site.objects.clear_cache()
site_settings = Site.objects.get_current().settings
assert site_settings.customer_set_password_url == customer_set_password_url