Skip to content
Merged
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: 3 additions & 4 deletions litestar/security/jwt/token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import dataclasses
from collections.abc import Sequence # noqa: TC003
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, TypedDict
Expand All @@ -11,8 +12,6 @@
from litestar.exceptions import ImproperlyConfiguredException, NotAuthorizedException

if TYPE_CHECKING:
from collections.abc import Sequence

from typing_extensions import Self

__all__ = (
Expand Down Expand Up @@ -59,8 +58,8 @@ class Token:
"""Issued at - should always be current now."""
iss: str | None = field(default=None)
"""Issuer - optional unique identifier for the issuer."""
aud: str | None = field(default=None)
"""Audience - intended audience."""
aud: str | Sequence[str] | None = field(default=None)
"""Audience - intended audience(s)."""
jti: str | None = field(default=None)
"""JWT ID - a unique identifier of the JWT between different issuers."""
extras: dict[str, Any] = field(default_factory=dict)
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test_security/test_jwt/test_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,34 @@ def test_strict_aud_with_one_element_sequence(audience: str | list[str]) -> None
)


@pytest.mark.parametrize(
"audience",
[
pytest.param(None, id="None"),
pytest.param("foo", id="String"),
pytest.param("not-foo", id="InvalidAudience"),
pytest.param(["foo", "bar"], id="List"),
],
)
def test_validate_audience(audience: str | list[str]) -> None:
secret = secrets.token_hex()
encoded = Token(exp=datetime.now() + timedelta(days=1), sub="foo", aud=["foo", "bar"]).encode(secret, "HS256")

def decode() -> None:
Token.decode(
encoded,
secret=secret,
algorithm="HS256",
audience=audience,
)

if audience != "not-foo":
decode()
else:
with pytest.raises(NotAuthorizedException):
decode()


def test_custom_decode_payload() -> None:
@dataclasses.dataclass
class CustomToken(Token):
Expand Down
Loading