Skip to content

RequestToken#

authx.schema.RequestToken #

Bases: BaseModel

token class-attribute instance-attribute #

token = Field(..., description='The token to verify')

csrf class-attribute instance-attribute #

csrf = None

type class-attribute instance-attribute #

type = 'access'

location instance-attribute #

location

verify #

verify(key, algorithms=None, audience=None, issuer=None, verify_jwt=True, verify_type=True, verify_csrf=True, verify_fresh=False)
PARAMETER DESCRIPTION
key

TYPE: str

algorithms

TYPE: Optional[Sequence[AlgorithmType]] DEFAULT: None

audience

TYPE: Optional[StringOrSequence] DEFAULT: None

issuer

TYPE: Optional[str] DEFAULT: None

verify_jwt

TYPE: bool DEFAULT: True

verify_type

TYPE: bool DEFAULT: True

verify_csrf

TYPE: bool DEFAULT: True

verify_fresh

TYPE: bool DEFAULT: False

Source code in authx/schema.py
def verify(
    self,
    key: str,
    algorithms: Optional[Sequence[AlgorithmType]] = None,
    audience: Optional[StringOrSequence] = None,
    issuer: Optional[str] = None,
    verify_jwt: bool = True,
    verify_type: bool = True,
    verify_csrf: bool = True,
    verify_fresh: bool = False,
) -> TokenPayload:
    if algorithms is None:  # pragma: no cover
        algorithms = ["HS256"]  # pragma: no cover
    try:
        decoded_token = decode_token(
            token=self.token,
            key=key,
            algorithms=algorithms,
            verify=verify_jwt,
            audience=audience,
            issuer=issuer,
        )
        payload = (
            TokenPayload.model_validate(decoded_token)
            if PYDANTIC_V2
            else TokenPayload(**decoded_token)
        )
    except JWTDecodeError as e:
        raise JWTDecodeError(*e.args) from e
    except ValidationError as e:
        raise JWTDecodeError(*e.args) from e

    if verify_type and (self.type != payload.type):
        error_msg = f"'{self.type}' token required, '{payload.type}' token received"
        if self.type == "access":
            raise AccessTokenRequiredError(error_msg)
        elif self.type == "refresh":  # pragma: no cover
            raise RefreshTokenRequiredError(error_msg)  # pragma: no cover
        raise TokenTypeError(error_msg)  # pragma: no cover

    if verify_fresh and not payload.fresh:
        raise FreshTokenRequiredError("Fresh token required")

    if verify_csrf and self.location == "cookies":
        if self.csrf is None:
            raise CSRFError(f"Missing CSRF token in {self.location}")
        if payload.csrf is None:
            raise CSRFError("Cookies token missing CSRF claim")  # pragma: no cover
        if not compare_digest(self.csrf, payload.csrf):
            raise CSRFError("CSRF token mismatch")

    return payload