Skip to content
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
7 changes: 4 additions & 3 deletions jwt/api_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ def encode(
if "iss" in payload and not isinstance(payload["iss"], str):
raise TypeError("Issuer (iss) must be a string.")

# Validate sub must be string
if "sub" in payload and not isinstance(payload["sub"], str):
raise TypeError("Subject (sub) must be a string.")

json_payload = self._encode_payload(
payload,
headers=headers,
Expand Down Expand Up @@ -427,9 +431,6 @@ def _validate_sub(
if "sub" not in payload:
return

if not isinstance(payload["sub"], str):
raise InvalidSubjectError("Subject must be a string")

if subject is not None:
if payload.get("sub") != subject:
raise InvalidSubjectError("Invalid subject")
Expand Down
9 changes: 5 additions & 4 deletions tests/test_api_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,15 +876,16 @@ def test_decode_missing_sub_but_required_claim(self, jwt):
token, secret, algorithms=["HS256"], options={"require": ["sub"]}
)

def test_decode_invalid_int_sub_claim(self, jwt):
def test_encode_with_invalid_int_sub_claim(self, jwt):
payload = {
"sub": 1224344,
}
secret = "your-256-bit-secret"
token = jwt.encode(payload, secret, algorithm="HS256")

with pytest.raises(InvalidSubjectError):
jwt.decode(token, secret, algorithms=["HS256"])
with pytest.raises(TypeError) as exc_info:
jwt.encode(payload, secret, algorithm="HS256")

assert "Subject (sub) must be a string" in str(exc_info.value)

def test_decode_with_valid_sub_claim(self, jwt):
payload = {
Expand Down
Loading