Skip to content

RequestToken

Bases: BaseModel

Base model for token data retrieved from requests

Parameters:

Name Type Description Default
type TokenType

Type of token. Defaults to access.

required
token Optional[str]

The token retrieved from the request. Defaults to None.

required
csrf Optional[str]

CSRF Value in request if detailed. Defaults to None.

required
location TokenLocation

Where the token was found in request.

required
Source code in fastjwt/models.py
class RequestToken(BaseModel):
    """Base model for token data retrieved from requests

    Args:
        type (TokenType): Type of token. Defaults to access.
        token (Optional[str]): The token retrieved from the request. Defaults to None.
        csrf (Optional[str]): CSRF Value in request if detailed. Defaults to None.
        location (TokenLocation): Where the token was found in request.
    """

    token: Optional[str] = None
    csrf: Optional[str] = None
    type: TokenType = "access"
    location: TokenLocation

    def verify(
        self,
        key: str,
        algorithms: Sequence[AlgorithmType] = ["HS256"],
        audience: Optional[StrOrSeq] = None,
        issuer: Optional[str] = None,
        verify_jwt: bool = True,
        verify_type: bool = True,
        verify_csrf: bool = True,
        verify_fresh: bool = False,
    ) -> TokenPayload:
        """Verify a RequestToken

        Args:
            key (str): Secret to decode the token
            algorithms (Sequence[AlgorithmType], optional): Algorithms to use to decode the token. Defaults to ["HS256"].
            audience (Optional[StrOrSeq], optional): Audience claim to verify. Defaults to None.
            issuer (Optional[str], optional): Issuer claim to verify. Defaults to None.
            verify_jwt (bool, optional): Enable base JWT verification. Defaults to True.
            verify_type (bool, optional): Enable token type verification. Defaults to True.
            verify_csrf (bool, optional): Enable CSRF verification. Defaults to True.
            verify_fresh (bool, optional): Enable token freshness verification. Defaults to False.

        Raises:
            JWTDecodeError: Error while decoding the token
            JWTDecodeError: The base JWT verification step has failed
            FreshTokenRequiredError: The token is not fresh
            CSRFError: A CSRF token is missing in the request
            CSRFError: No CSRF claim is contained in the token
            CSRFError: CSRF double submit does not match

        Returns:
            TokenPayload: The payload encoded in the token
        """
        # JWT Base Verification
        try:
            decoded_token = decode_token(
                token=self.token,
                key=key,
                algorithms=algorithms,
                verify=verify_jwt,
                audience=audience,
                issuer=issuer,
            )
            # Parse payload
            payload = TokenPayload.parse_obj(decoded_token)
        except JWTDecodeError as e:
            raise JWTDecodeError(*e.args)
        except ValidationError as e:
            raise JWTDecodeError(*e.args)

        # TODO Verify Headers

        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":
                raise RefreshTokenRequiredError(error_msg)
            raise TokenTypeError(error_msg)

        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("Missing CSRF in request")
            if payload.csrf is None:
                raise CSRFError("Missing 'csrf' claim")
            if not compare_digest(self.csrf, payload.csrf):
                raise CSRFError("CSRF double submit does not match")

        return payload

verify(key, algorithms=['HS256'], audience=None, issuer=None, verify_jwt=True, verify_type=True, verify_csrf=True, verify_fresh=False)

Verify a RequestToken

Parameters:

Name Type Description Default
key str

Secret to decode the token

required
algorithms Sequence[AlgorithmType]

Algorithms to use to decode the token. Defaults to ["HS256"].

['HS256']
audience Optional[StrOrSeq]

Audience claim to verify. Defaults to None.

None
issuer Optional[str]

Issuer claim to verify. Defaults to None.

None
verify_jwt bool

Enable base JWT verification. Defaults to True.

True
verify_type bool

Enable token type verification. Defaults to True.

True
verify_csrf bool

Enable CSRF verification. Defaults to True.

True
verify_fresh bool

Enable token freshness verification. Defaults to False.

False

Raises:

Type Description
JWTDecodeError

Error while decoding the token

JWTDecodeError

The base JWT verification step has failed

FreshTokenRequiredError

The token is not fresh

CSRFError

A CSRF token is missing in the request

CSRFError

No CSRF claim is contained in the token

CSRFError

CSRF double submit does not match

Returns:

Name Type Description
TokenPayload TokenPayload

The payload encoded in the token

Source code in fastjwt/models.py
def verify(
    self,
    key: str,
    algorithms: Sequence[AlgorithmType] = ["HS256"],
    audience: Optional[StrOrSeq] = None,
    issuer: Optional[str] = None,
    verify_jwt: bool = True,
    verify_type: bool = True,
    verify_csrf: bool = True,
    verify_fresh: bool = False,
) -> TokenPayload:
    """Verify a RequestToken

    Args:
        key (str): Secret to decode the token
        algorithms (Sequence[AlgorithmType], optional): Algorithms to use to decode the token. Defaults to ["HS256"].
        audience (Optional[StrOrSeq], optional): Audience claim to verify. Defaults to None.
        issuer (Optional[str], optional): Issuer claim to verify. Defaults to None.
        verify_jwt (bool, optional): Enable base JWT verification. Defaults to True.
        verify_type (bool, optional): Enable token type verification. Defaults to True.
        verify_csrf (bool, optional): Enable CSRF verification. Defaults to True.
        verify_fresh (bool, optional): Enable token freshness verification. Defaults to False.

    Raises:
        JWTDecodeError: Error while decoding the token
        JWTDecodeError: The base JWT verification step has failed
        FreshTokenRequiredError: The token is not fresh
        CSRFError: A CSRF token is missing in the request
        CSRFError: No CSRF claim is contained in the token
        CSRFError: CSRF double submit does not match

    Returns:
        TokenPayload: The payload encoded in the token
    """
    # JWT Base Verification
    try:
        decoded_token = decode_token(
            token=self.token,
            key=key,
            algorithms=algorithms,
            verify=verify_jwt,
            audience=audience,
            issuer=issuer,
        )
        # Parse payload
        payload = TokenPayload.parse_obj(decoded_token)
    except JWTDecodeError as e:
        raise JWTDecodeError(*e.args)
    except ValidationError as e:
        raise JWTDecodeError(*e.args)

    # TODO Verify Headers

    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":
            raise RefreshTokenRequiredError(error_msg)
        raise TokenTypeError(error_msg)

    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("Missing CSRF in request")
        if payload.csrf is None:
            raise CSRFError("Missing 'csrf' claim")
        if not compare_digest(self.csrf, payload.csrf):
            raise CSRFError("CSRF double submit does not match")

    return payload