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