Skip to content

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

Better way of handling token expiration and old type of jwt tokens

Maciej Korycinski7609a4031915
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 8829435c3a..b960c5e161 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -1,3 +1,5 @@
+from jwt.exceptions import PyJWTError
+
from ..checkout.error_codes import CheckoutErrorCode
@@ -39,3 +41,7 @@ class PermissionDenied(Exception):
if message is None:
message = default_message
super().__init__(message)
+
+
+class ExpiredUserSignatureError(PyJWTError):
+ pass
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 912f76237f..e2d191912f 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -5,8 +5,10 @@ import graphene
import jwt
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
+from jwt import InvalidTokenError
from ..account.models import User
+from .exceptions import ExpiredUserSignatureError
JWT_ALGORITHM = "HS256"
JWT_AUTH_HEADER = "HTTP_AUTHORIZATION"
@@ -16,13 +18,9 @@ JWT_REFRESH_TYPE = "refresh"
JWT_REFRESH_TOKEN_COOKIE_NAME = "refreshToken"
-def jwt_base_payload(exp_delta: Optional[timedelta] = None) -> Dict[str, Any]:
+def jwt_base_payload(exp_delta: timedelta) -> Dict[str, Any]:
utc_now = datetime.utcnow()
- payload = {
- "iat": utc_now,
- }
- if exp_delta:
- payload["exp"] = utc_now + exp_delta
+ payload = {"iat": utc_now, "exp": utc_now + exp_delta}
return payload
@@ -32,8 +30,6 @@ def jwt_user_payload(
exp_delta: timedelta,
additional_payload: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
- if not settings.JWT_EXPIRE:
- exp_delta = None # type: ignore
payload = jwt_base_payload(exp_delta)
payload.update(
@@ -58,7 +54,10 @@ def jwt_encode(payload: Dict[str, Any]) -> str:
def jwt_decode(token: str) -> Dict[str, Any]:
return jwt.decode(
- token, settings.SECRET_KEY, algorithms=JWT_ALGORITHM # type: ignore
+ token,
+ settings.SECRET_KEY, # type: ignore
+ algorithms=JWT_ALGORITHM,
+ verify_expiration=settings.JWT_EXPIRE,
)
@@ -96,13 +95,24 @@ def get_token_from_request(request: WSGIRequest) -> Optional[str]:
def get_user_from_payload(payload: Dict[str, Any]) -> Optional[User]:
user = User.objects.filter(email=payload["email"], is_active=True).first()
- if user and user.jwt_token_key == payload["token"]:
- return user
- return None
+ user_jwt_token = payload.get("token")
+ if not user_jwt_token or not user:
+ raise InvalidTokenError(
+ "Invalid token. Create new one by using tokenCreate mutation."
+ )
+ if user.jwt_token_key != user_jwt_token:
+ raise ExpiredUserSignatureError(
+ "User requested to expire this token. Create new one by using tokenCreate "
+ "mutation."
+ )
+ return user
def get_user_from_access_token(token: str) -> Optional[User]:
payload = jwt_decode(token)
- if payload["type"] != JWT_ACCESS_TYPE:
- return None
+ jwt_type = payload.get("type")
+ if jwt_type != JWT_ACCESS_TYPE:
+ raise InvalidTokenError(
+ "Invalid token. Create new one by using tokenCreate mutation."
+ )
return get_user_from_payload(payload)
diff --git a/saleor/core/tests/test_auth_backend.py b/saleor/core/tests/test_auth_backend.py
index cc9bf4284b..8bf0e00aa5 100644
--- a/saleor/core/tests/test_auth_backend.py
+++ b/saleor/core/tests/test_auth_backend.py
@@ -1,14 +1,16 @@
import jwt
import pytest
from freezegun import freeze_time
-from jwt import ExpiredSignatureError, InvalidSignatureError
+from jwt import ExpiredSignatureError, InvalidSignatureError, InvalidTokenError
from ..auth_backend import JSONWebTokenBackend
+from ..exceptions import ExpiredUserSignatureError
from ..jwt import (
JWT_ACCESS_TYPE,
JWT_ALGORITHM,
create_access_token,
create_refresh_token,
+ jwt_encode,
jwt_user_payload,
)
@@ -27,14 +29,16 @@ def test_user_deactivated(rf, staff_user):
access_token = create_access_token(staff_user)
request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")
backend = JSONWebTokenBackend()
- assert backend.authenticate(request) is None
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
def test_incorect_type_of_token(rf, staff_user):
token = create_refresh_token(staff_user)
request = rf.request(HTTP_AUTHORIZATION=f"JWT {token}")
backend = JSONWebTokenBackend()
- assert backend.authenticate(request) is None
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
def test_incorrect_token(rf, staff_user, settings):
@@ -72,7 +76,8 @@ def test_user_doesnt_exist(rf, staff_user):
staff_user.delete()
request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")
backend = JSONWebTokenBackend()
- assert backend.authenticate(request) is None
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
def test_user_deactivated_token(rf, staff_user):
@@ -81,4 +86,31 @@ def test_user_deactivated_token(rf, staff_user):
staff_user.save()
request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")
backend = JSONWebTokenBackend()
- assert backend.authenticate(request) is None
+ with pytest.raises(ExpiredUserSignatureError):
+ backend.authenticate(request)
+
+
+def test_user_payload_doesnt_have_user_token(rf, staff_user, settings):
+ access_payload = jwt_user_payload(
+ staff_user, JWT_ACCESS_TYPE, settings.JWT_TTL_ACCESS
+ )
+ del access_payload["token"]
+ access_token = jwt_encode(access_payload)
+
+ request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")
+ backend = JSONWebTokenBackend()
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
+
+
+def test_user_has_old_token_type(rf, staff_user, settings):
+ settings.JWT_EXPIRE = False
+ access_token = (
+ "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFkbWluQGV4YW1wbGUuY29tIiwiZ"
+ "XhwIjoxNTYwMTczNDI2LCJvcmlnSWF0IjoxNTYwMTczMTI2fQ.QrYkGfEqnwC-d--EHATAfXoWURJf"
+ "lFfbntR7BESI9mg"
+ )
+ request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")
+ backend = JSONWebTokenBackend()
+ with pytest.raises(InvalidTokenError):
+ backend.authenticate(request)
diff --git a/saleor/graphql/account/mutations/jwt.py b/saleor/graphql/account/mutations/jwt.py
index 81e05b1ea2..82fabb5938 100644
--- a/saleor/graphql/account/mutations/jwt.py
+++ b/saleor/graphql/account/mutations/jwt.py
@@ -40,7 +40,10 @@ def get_payload(token):
def get_user(payload):
- user = get_user_from_payload(payload)
+ try:
+ user = get_user_from_payload(payload)
+ except Exception:
+ user = None
if not user:
raise ValidationError(
"Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value
diff --git a/saleor/graphql/account/tests/mutations/test_tokens_deactivate_all.py b/saleor/graphql/account/tests/mutations/test_tokens_deactivate_all.py
index 92acfd83f1..22606ed916 100644
--- a/saleor/graphql/account/tests/mutations/test_tokens_deactivate_all.py
+++ b/saleor/graphql/account/tests/mutations/test_tokens_deactivate_all.py
@@ -1,3 +1,5 @@
+import json
+
from django.middleware.csrf import _get_new_csrf_token
from freezegun import freeze_time
@@ -52,7 +54,12 @@ def test_deactivate_all_user_tokens_access_token(user_api_client, customer_user)
query = "{me { id }}"
response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
+ content = json.loads(response.content.decode("utf8"))
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["extensions"]["exception"]["code"] == (
+ "ExpiredUserSignatureError"
+ )
+
assert content["data"]["me"] is None