utils.py 16 KB

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