utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import datetime
  2. from typing import Any
  3. from typing import Optional
  4. import jwt
  5. from flask import _request_ctx_stack
  6. from flask import Response
  7. from werkzeug.local import LocalProxy
  8. from flask_jwt_extended.config import config
  9. from flask_jwt_extended.internal_utils import get_jwt_manager
  10. # Proxy to access the current user
  11. current_user = LocalProxy(lambda: get_current_user())
  12. def get_jwt() -> dict:
  13. """
  14. In a protected endpoint, this will return the python dictionary which has
  15. the payload of the JWT that is accessing the endpoint. If no JWT is present
  16. due to ``jwt_required(optional=True)``, an empty dictionary is returned.
  17. :return:
  18. The payload (claims) of the JWT in the current request
  19. """
  20. decoded_jwt = getattr(_request_ctx_stack.top, "jwt", None)
  21. if decoded_jwt is None:
  22. raise RuntimeError(
  23. "You must call `@jwt_required()` or `verify_jwt_in_request()` "
  24. "before using this method"
  25. )
  26. return decoded_jwt
  27. def get_jwt_header() -> dict:
  28. """
  29. In a protected endpoint, this will return the python dictionary which has
  30. the header of the JWT that is accessing the endpoint. If no JWT is present
  31. due to ``jwt_required(optional=True)``, an empty dictionary is returned.
  32. :return:
  33. The headers of the JWT in the current request
  34. """
  35. decoded_header = getattr(_request_ctx_stack.top, "jwt_header", None)
  36. if decoded_header is None:
  37. raise RuntimeError(
  38. "You must call `@jwt_required()` or `verify_jwt_in_request()` "
  39. "before using this method"
  40. )
  41. return decoded_header
  42. def get_jwt_identity() -> Any:
  43. """
  44. In a protected endpoint, this will return the identity of the JWT that is
  45. accessing the endpoint. If no JWT is present due to
  46. ``jwt_required(optional=True)``, ``None`` is returned.
  47. :return:
  48. The identity of the JWT in the current request
  49. """
  50. return get_jwt().get(config.identity_claim_key, None)
  51. def get_jwt_request_location() -> Optional[str]:
  52. """
  53. In a protected endpoint, this will return the "location" at which the JWT
  54. that is accessing the endpoint was found--e.g., "cookies", "query-string",
  55. "headers", or "json". If no JWT is present due to ``jwt_required(optional=True)``,
  56. None is returned.
  57. :return:
  58. The location of the JWT in the current request; e.g., "cookies",
  59. "query-string", "headers", or "json"
  60. """
  61. return getattr(_request_ctx_stack.top, "jwt_location", None)
  62. def get_current_user() -> Any:
  63. """
  64. In a protected endpoint, this will return the user object for the JWT that
  65. is accessing the endpoint.
  66. This is only usable if :meth:`~flask_jwt_extended.JWTManager.user_lookup_loader`
  67. is configured. If the user loader callback is not being used, this will
  68. raise an error.
  69. If no JWT is present due to ``jwt_required(optional=True)``, ``None`` is returned.
  70. :return:
  71. The current user object for the JWT in the current request
  72. """
  73. get_jwt() # Raise an error if not in a decorated context
  74. jwt_user_dict = getattr(_request_ctx_stack.top, "jwt_user", None)
  75. if jwt_user_dict is None:
  76. raise RuntimeError(
  77. "You must provide a `@jwt.user_lookup_loader` callback to use "
  78. "this method"
  79. )
  80. return jwt_user_dict["loaded_user"]
  81. def decode_token(
  82. encoded_token: str, csrf_value: str = None, allow_expired: bool = False
  83. ) -> dict:
  84. """
  85. Returns the decoded token (python dict) from an encoded JWT. This does all
  86. the checks to ensure that the decoded token is valid before returning it.
  87. This will not fire the user loader callbacks, save the token for access
  88. in protected endpoints, checked if a token is revoked, etc. This is puerly
  89. used to ensure that a JWT is valid.
  90. :param encoded_token:
  91. The encoded JWT to decode.
  92. :param csrf_value:
  93. Expected CSRF double submit value (optional).
  94. :param allow_expired:
  95. If ``True``, do not raise an error if the JWT is expired. Defaults to ``False``
  96. :return:
  97. Dictionary containing the payload of the JWT decoded JWT.
  98. """
  99. jwt_manager = get_jwt_manager()
  100. return jwt_manager._decode_jwt_from_config(encoded_token, csrf_value, allow_expired)
  101. def create_access_token(
  102. identity: Any,
  103. fresh: bool = False,
  104. expires_delta: datetime.timedelta = None,
  105. additional_claims=None,
  106. additional_headers=None,
  107. ):
  108. """
  109. Create a new access token.
  110. :param identity:
  111. The identity of this token. It can be any data that is json serializable.
  112. You can use :meth:`~flask_jwt_extended.JWTManager.user_identity_loader`
  113. to define a callback function to convert any object passed in into a json
  114. serializable format.
  115. :param fresh:
  116. If this token should be marked as fresh, and can thus access endpoints
  117. protected with ``@jwt_required(fresh=True)``. Defaults to ``False``.
  118. This value can also be a ``datetime.timedelta``, which indicate
  119. how long this token will be considered fresh.
  120. :param expires_delta:
  121. A ``datetime.timedelta`` for how long this token should last before it
  122. expires. Set to False to disable expiration. If this is None, it will use
  123. the ``JWT_ACCESS_TOKEN_EXPIRES`` config value (see :ref:`Configuration Options`)
  124. :param additional_claims:
  125. Optional. A hash of claims to include in the access token. These claims are
  126. merged into the default claims (exp, iat, etc) and claims returned from the
  127. :meth:`~flask_jwt_extended.JWTManager.additional_claims_loader` callback.
  128. On conflict, these claims take presidence.
  129. :param headers:
  130. Optional. A hash of headers to include in the access token. These headers
  131. are merged into the default headers (alg, typ) and headers returned from
  132. the :meth:`~flask_jwt_extended.JWTManager.additional_headers_loader`
  133. callback. On conflict, these headers take presidence.
  134. :return:
  135. An encoded access token
  136. """
  137. jwt_manager = get_jwt_manager()
  138. return jwt_manager._encode_jwt_from_config(
  139. claims=additional_claims,
  140. expires_delta=expires_delta,
  141. fresh=fresh,
  142. headers=additional_headers,
  143. identity=identity,
  144. token_type="access",
  145. )
  146. def create_refresh_token(
  147. identity: Any,
  148. expires_delta: datetime.timedelta = None,
  149. additional_claims=None,
  150. additional_headers=None,
  151. ):
  152. """
  153. Create a new refresh token.
  154. :param identity:
  155. The identity of this token. It can be any data that is json serializable.
  156. You can use :meth:`~flask_jwt_extended.JWTManager.user_identity_loader`
  157. to define a callback function to convert any object passed in into a json
  158. serializable format.
  159. :param expires_delta:
  160. A ``datetime.timedelta`` for how long this token should last before it expires.
  161. Set to False to disable expiration. If this is None, it will use the
  162. ``JWT_REFRESH_TOKEN_EXPIRES`` config value (see :ref:`Configuration Options`)
  163. :param additional_claims:
  164. Optional. A hash of claims to include in the refresh token. These claims are
  165. merged into the default claims (exp, iat, etc) and claims returned from the
  166. :meth:`~flask_jwt_extended.JWTManager.additional_claims_loader` callback.
  167. On conflict, these claims take presidence.
  168. :param headers:
  169. Optional. A hash of headers to include in the refresh token. These headers
  170. are merged into the default headers (alg, typ) and headers returned from the
  171. :meth:`~flask_jwt_extended.JWTManager.additional_headers_loader` callback.
  172. On conflict, these headers take presidence.
  173. :return:
  174. An encoded refresh token
  175. """
  176. jwt_manager = get_jwt_manager()
  177. return jwt_manager._encode_jwt_from_config(
  178. claims=additional_claims,
  179. expires_delta=expires_delta,
  180. fresh=False,
  181. headers=additional_headers,
  182. identity=identity,
  183. token_type="refresh",
  184. )
  185. def get_unverified_jwt_headers(encoded_token: str) -> dict:
  186. """
  187. Returns the Headers of an encoded JWT without verifying the signature of the JWT.
  188. :param encoded_token:
  189. The encoded JWT to get the Header from.
  190. :return:
  191. JWT header parameters as python dict()
  192. """
  193. return jwt.get_unverified_header(encoded_token)
  194. def get_jti(encoded_token: str) -> Optional[str]:
  195. """
  196. Returns the JTI (unique identifier) of an encoded JWT
  197. :param encoded_token:
  198. The encoded JWT to get the JTI from.
  199. :return:
  200. The JTI (unique identifier) of a JWT, if it is present.
  201. """
  202. return decode_token(encoded_token).get("jti")
  203. def get_csrf_token(encoded_token: str) -> str:
  204. """
  205. Returns the CSRF double submit token from an encoded JWT.
  206. :param encoded_token:
  207. The encoded JWT
  208. :return:
  209. The CSRF double submit token (string)
  210. """
  211. token = decode_token(encoded_token)
  212. return token["csrf"]
  213. def set_access_cookies(
  214. response: Response, encoded_access_token: str, max_age=None, domain=None
  215. ) -> None:
  216. """
  217. Modifiy a Flask Response to set a cookie containing the access JWT.
  218. Also sets the corresponding CSRF cookies if ``JWT_CSRF_IN_COOKIES`` is ``True``
  219. (see :ref:`Configuration Options`)
  220. :param response:
  221. A Flask Response object.
  222. :param encoded_access_token:
  223. The encoded access token to set in the cookies.
  224. :param max_age:
  225. The max age of the cookie. If this is None, it will use the
  226. ``JWT_SESSION_COOKIE`` option (see :ref:`Configuration Options`). Otherwise,
  227. it will use this as the cookies ``max-age`` and the JWT_SESSION_COOKIE option
  228. will be ignored. Values should be the number of seconds (as an integer).
  229. :param domain:
  230. The domain of the cookie. If this is None, it will use the
  231. ``JWT_COOKIE_DOMAIN`` option (see :ref:`Configuration Options`). Otherwise,
  232. it will use this as the cookies ``domain`` and the JWT_COOKIE_DOMAIN option
  233. will be ignored.
  234. """
  235. response.set_cookie(
  236. config.access_cookie_name,
  237. value=encoded_access_token,
  238. max_age=max_age or config.cookie_max_age,
  239. secure=config.cookie_secure,
  240. httponly=True,
  241. domain=domain or config.cookie_domain,
  242. path=config.access_cookie_path,
  243. samesite=config.cookie_samesite,
  244. )
  245. if config.csrf_protect and config.csrf_in_cookies:
  246. response.set_cookie(
  247. config.access_csrf_cookie_name,
  248. value=get_csrf_token(encoded_access_token),
  249. max_age=max_age or config.cookie_max_age,
  250. secure=config.cookie_secure,
  251. httponly=False,
  252. domain=domain or config.cookie_domain,
  253. path=config.access_csrf_cookie_path,
  254. samesite=config.cookie_samesite,
  255. )
  256. def set_refresh_cookies(
  257. response: Response,
  258. encoded_refresh_token: str,
  259. max_age: int = None,
  260. domain: str = None,
  261. ) -> None:
  262. """
  263. Modifiy a Flask Response to set a cookie containing the refresh JWT.
  264. Also sets the corresponding CSRF cookies if ``JWT_CSRF_IN_COOKIES`` is ``True``
  265. (see :ref:`Configuration Options`)
  266. :param response:
  267. A Flask Response object.
  268. :param encoded_refresh_token:
  269. The encoded refresh token to set in the cookies.
  270. :param max_age:
  271. The max age of the cookie. If this is None, it will use the
  272. ``JWT_SESSION_COOKIE`` option (see :ref:`Configuration Options`). Otherwise,
  273. it will use this as the cookies ``max-age`` and the JWT_SESSION_COOKIE option
  274. will be ignored. Values should be the number of seconds (as an integer).
  275. :param domain:
  276. The domain of the cookie. If this is None, it will use the
  277. ``JWT_COOKIE_DOMAIN`` option (see :ref:`Configuration Options`). Otherwise,
  278. it will use this as the cookies ``domain`` and the JWT_COOKIE_DOMAIN option
  279. will be ignored.
  280. """
  281. response.set_cookie(
  282. config.refresh_cookie_name,
  283. value=encoded_refresh_token,
  284. max_age=max_age or config.cookie_max_age,
  285. secure=config.cookie_secure,
  286. httponly=True,
  287. domain=domain or config.cookie_domain,
  288. path=config.refresh_cookie_path,
  289. samesite=config.cookie_samesite,
  290. )
  291. if config.csrf_protect and config.csrf_in_cookies:
  292. response.set_cookie(
  293. config.refresh_csrf_cookie_name,
  294. value=get_csrf_token(encoded_refresh_token),
  295. max_age=max_age or config.cookie_max_age,
  296. secure=config.cookie_secure,
  297. httponly=False,
  298. domain=domain or config.cookie_domain,
  299. path=config.refresh_csrf_cookie_path,
  300. samesite=config.cookie_samesite,
  301. )
  302. def unset_jwt_cookies(response: Response, domain: str = None) -> None:
  303. """
  304. Modifiy a Flask Response to delete the cookies containing access or refresh
  305. JWTs. Also deletes the corresponding CSRF cookies if applicable.
  306. :param response:
  307. A Flask Response object
  308. """
  309. unset_access_cookies(response, domain)
  310. unset_refresh_cookies(response, domain)
  311. def unset_access_cookies(response: Response, domain: str = None) -> None:
  312. """
  313. Modifiy a Flask Response to delete the cookie containing an access JWT.
  314. Also deletes the corresponding CSRF cookie if applicable.
  315. :param response:
  316. A Flask Response object
  317. :param domain:
  318. The domain of the cookie. If this is None, it will use the
  319. ``JWT_COOKIE_DOMAIN`` option (see :ref:`Configuration Options`). Otherwise,
  320. it will use this as the cookies ``domain`` and the JWT_COOKIE_DOMAIN option
  321. will be ignored.
  322. """
  323. response.set_cookie(
  324. config.access_cookie_name,
  325. value="",
  326. expires=0,
  327. secure=config.cookie_secure,
  328. httponly=True,
  329. domain=domain or config.cookie_domain,
  330. path=config.access_cookie_path,
  331. samesite=config.cookie_samesite,
  332. )
  333. if config.csrf_protect and config.csrf_in_cookies:
  334. response.set_cookie(
  335. config.access_csrf_cookie_name,
  336. value="",
  337. expires=0,
  338. secure=config.cookie_secure,
  339. httponly=False,
  340. domain=domain or config.cookie_domain,
  341. path=config.access_csrf_cookie_path,
  342. samesite=config.cookie_samesite,
  343. )
  344. def unset_refresh_cookies(response: Response, domain: str = None) -> None:
  345. """
  346. Modifiy a Flask Response to delete the cookie containing a refresh JWT.
  347. Also deletes the corresponding CSRF cookie if applicable.
  348. :param response:
  349. A Flask Response object
  350. :param domain:
  351. The domain of the cookie. If this is None, it will use the
  352. ``JWT_COOKIE_DOMAIN`` option (see :ref:`Configuration Options`). Otherwise,
  353. it will use this as the cookies ``domain`` and the JWT_COOKIE_DOMAIN option
  354. will be ignored.
  355. """
  356. response.set_cookie(
  357. config.refresh_cookie_name,
  358. value="",
  359. expires=0,
  360. secure=config.cookie_secure,
  361. httponly=True,
  362. domain=domain or config.cookie_domain,
  363. path=config.refresh_cookie_path,
  364. samesite=config.cookie_samesite,
  365. )
  366. if config.csrf_protect and config.csrf_in_cookies:
  367. response.set_cookie(
  368. config.refresh_csrf_cookie_name,
  369. value="",
  370. expires=0,
  371. secure=config.cookie_secure,
  372. httponly=False,
  373. domain=domain or config.cookie_domain,
  374. path=config.refresh_csrf_cookie_path,
  375. samesite=config.cookie_samesite,
  376. )