Skip to content

JWTStr

JWTStr

Bases: str

A string subclass with structural validation for JWT (JSON Web Token) format.

Only the structure is checked: three urlsafe-base64 segments whose header and payload decode to JSON objects. The signature is neither verified nor inspected, so the payload of a JWTStr built from untrusted input is attacker-controlled data — use JWTModel.from_token() to verify.

Examples:

from pydantic import BaseModel

from pydantic_jwt import JWTStr


class Auth(BaseModel):
    token: JWTStr


auth = Auth(token='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dGVzdA')
print(auth.token.header)
#> {'alg': 'HS256'}
print(auth.token.algorithm)
#> 'HS256'
print(auth.token.payload)
#> {'sub': '1234567890'}
print(auth.token.signature)
#> b'test'

header property

header: dict[str, Any]

Return the decoded JWT header.

algorithm property

algorithm: str | None

Return the alg value from the header, or None if it is absent.

payload property

payload: dict[str, Any]

Return the decoded JWT payload.

signature property

signature: bytes

Return the raw JWT signature bytes.

validate classmethod

validate(jwt: str) -> bool

Return whether the value is structurally a valid JWT, without raising.

Parameters:

Name Type Description Default
jwt str

The value to inspect. A non-string returns False rather than raising.

required

Returns:

Type Description
bool

True if the value would construct a JWTStr.

Source code in pydantic_jwt/str.py
@classmethod
def validate(cls, jwt: str) -> bool:
    """Return whether the value is structurally a valid JWT, without raising.

    Args:
        jwt: The value to inspect. A non-string returns `False` rather than
            raising.

    Returns:
        `True` if the value would construct a `JWTStr`.
    """
    try:
        cls._validate(jwt)
    except PydanticCustomError:
        return False
    return True