config.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from datetime import datetime
  2. from datetime import timedelta
  3. from datetime import timezone
  4. from json import JSONEncoder
  5. from typing import Iterable
  6. from typing import List
  7. from typing import Optional
  8. from typing import Sequence
  9. from typing import Type
  10. from typing import Union
  11. from flask import current_app
  12. from jwt.algorithms import requires_cryptography
  13. from flask_jwt_extended.internal_utils import get_json_encoder
  14. from flask_jwt_extended.typing import ExpiresDelta
  15. class _Config(object):
  16. """
  17. Helper object for accessing and verifying options in this extension. This
  18. is meant for internal use of the application; modifying config options
  19. should be done with flasks ```app.config```.
  20. Default values for the configuration options are set in the jwt_manager
  21. object. All of these values are read only. This is simply a loose wrapper
  22. with some helper functionality for flasks `app.config`.
  23. """
  24. @property
  25. def is_asymmetric(self) -> bool:
  26. return self.algorithm in requires_cryptography
  27. @property
  28. def encode_key(self) -> str:
  29. return self._private_key if self.is_asymmetric else self._secret_key
  30. @property
  31. def decode_key(self) -> str:
  32. return self._public_key if self.is_asymmetric else self._secret_key
  33. @property
  34. def token_location(self) -> Sequence[str]:
  35. locations = current_app.config["JWT_TOKEN_LOCATION"]
  36. if isinstance(locations, str):
  37. locations = (locations,)
  38. elif not isinstance(locations, Iterable):
  39. raise RuntimeError("JWT_TOKEN_LOCATION must be a sequence or a set")
  40. elif not locations:
  41. raise RuntimeError(
  42. "JWT_TOKEN_LOCATION must contain at least one "
  43. 'of "headers", "cookies", "query_string", or "json"'
  44. )
  45. for location in locations:
  46. if location not in ("headers", "cookies", "query_string", "json"):
  47. raise RuntimeError(
  48. "JWT_TOKEN_LOCATION can only contain "
  49. '"headers", "cookies", "query_string", or "json"'
  50. )
  51. return locations
  52. @property
  53. def jwt_in_cookies(self) -> bool:
  54. return "cookies" in self.token_location
  55. @property
  56. def jwt_in_headers(self) -> bool:
  57. return "headers" in self.token_location
  58. @property
  59. def jwt_in_query_string(self) -> bool:
  60. return "query_string" in self.token_location
  61. @property
  62. def jwt_in_json(self) -> bool:
  63. return "json" in self.token_location
  64. @property
  65. def header_name(self) -> str:
  66. name = current_app.config["JWT_HEADER_NAME"]
  67. if not name:
  68. raise RuntimeError("JWT_ACCESS_HEADER_NAME cannot be empty")
  69. return name
  70. @property
  71. def header_type(self) -> str:
  72. return current_app.config["JWT_HEADER_TYPE"]
  73. @property
  74. def query_string_name(self) -> str:
  75. return current_app.config["JWT_QUERY_STRING_NAME"]
  76. @property
  77. def query_string_value_prefix(self) -> str:
  78. return current_app.config["JWT_QUERY_STRING_VALUE_PREFIX"]
  79. @property
  80. def access_cookie_name(self) -> str:
  81. return current_app.config["JWT_ACCESS_COOKIE_NAME"]
  82. @property
  83. def refresh_cookie_name(self) -> str:
  84. return current_app.config["JWT_REFRESH_COOKIE_NAME"]
  85. @property
  86. def access_cookie_path(self) -> str:
  87. return current_app.config["JWT_ACCESS_COOKIE_PATH"]
  88. @property
  89. def refresh_cookie_path(self) -> str:
  90. return current_app.config["JWT_REFRESH_COOKIE_PATH"]
  91. @property
  92. def cookie_secure(self) -> bool:
  93. return current_app.config["JWT_COOKIE_SECURE"]
  94. @property
  95. def cookie_domain(self) -> str:
  96. return current_app.config["JWT_COOKIE_DOMAIN"]
  97. @property
  98. def session_cookie(self) -> bool:
  99. return current_app.config["JWT_SESSION_COOKIE"]
  100. @property
  101. def cookie_samesite(self) -> str:
  102. return current_app.config["JWT_COOKIE_SAMESITE"]
  103. @property
  104. def json_key(self) -> str:
  105. return current_app.config["JWT_JSON_KEY"]
  106. @property
  107. def refresh_json_key(self) -> str:
  108. return current_app.config["JWT_REFRESH_JSON_KEY"]
  109. @property
  110. def cookie_csrf_protect(self) -> bool:
  111. return current_app.config["JWT_COOKIE_CSRF_PROTECT"]
  112. @property
  113. def csrf_request_methods(self) -> Iterable[str]:
  114. return current_app.config["JWT_CSRF_METHODS"]
  115. @property
  116. def csrf_in_cookies(self) -> bool:
  117. return current_app.config["JWT_CSRF_IN_COOKIES"]
  118. @property
  119. def access_csrf_cookie_name(self) -> str:
  120. return current_app.config["JWT_ACCESS_CSRF_COOKIE_NAME"]
  121. @property
  122. def refresh_csrf_cookie_name(self) -> str:
  123. return current_app.config["JWT_REFRESH_CSRF_COOKIE_NAME"]
  124. @property
  125. def access_csrf_cookie_path(self) -> str:
  126. return current_app.config["JWT_ACCESS_CSRF_COOKIE_PATH"]
  127. @property
  128. def refresh_csrf_cookie_path(self) -> str:
  129. return current_app.config["JWT_REFRESH_CSRF_COOKIE_PATH"]
  130. @property
  131. def access_csrf_header_name(self) -> str:
  132. return current_app.config["JWT_ACCESS_CSRF_HEADER_NAME"]
  133. @property
  134. def refresh_csrf_header_name(self) -> str:
  135. return current_app.config["JWT_REFRESH_CSRF_HEADER_NAME"]
  136. @property
  137. def csrf_check_form(self) -> bool:
  138. return current_app.config["JWT_CSRF_CHECK_FORM"]
  139. @property
  140. def access_csrf_field_name(self) -> str:
  141. return current_app.config["JWT_ACCESS_CSRF_FIELD_NAME"]
  142. @property
  143. def refresh_csrf_field_name(self) -> str:
  144. return current_app.config["JWT_REFRESH_CSRF_FIELD_NAME"]
  145. @property
  146. def access_expires(self) -> ExpiresDelta:
  147. delta = current_app.config["JWT_ACCESS_TOKEN_EXPIRES"]
  148. if type(delta) is int:
  149. delta = timedelta(seconds=delta)
  150. if delta is not False:
  151. try:
  152. # Basically runtime typechecking. Probably a better way to do
  153. # this with proper type checking
  154. delta + datetime.now(timezone.utc)
  155. except TypeError as e:
  156. err = (
  157. "must be able to add JWT_ACCESS_TOKEN_EXPIRES to datetime.datetime"
  158. )
  159. raise RuntimeError(err) from e
  160. return delta
  161. @property
  162. def refresh_expires(self) -> ExpiresDelta:
  163. delta = current_app.config["JWT_REFRESH_TOKEN_EXPIRES"]
  164. if type(delta) is int:
  165. delta = timedelta(seconds=delta)
  166. if delta is not False:
  167. # Basically runtime typechecking. Probably a better way to do
  168. # this with proper type checking
  169. try:
  170. delta + datetime.now(timezone.utc)
  171. except TypeError as e:
  172. err = (
  173. "must be able to add JWT_REFRESH_TOKEN_EXPIRES to datetime.datetime"
  174. )
  175. raise RuntimeError(err) from e
  176. return delta
  177. @property
  178. def algorithm(self) -> str:
  179. return current_app.config["JWT_ALGORITHM"]
  180. @property
  181. def decode_algorithms(self) -> List[str]:
  182. algorithms = current_app.config["JWT_DECODE_ALGORITHMS"]
  183. if not algorithms:
  184. return [self.algorithm]
  185. if self.algorithm not in algorithms:
  186. algorithms.append(self.algorithm)
  187. return algorithms
  188. @property
  189. def _secret_key(self) -> str:
  190. key = current_app.config["JWT_SECRET_KEY"]
  191. if not key:
  192. key = current_app.config.get("SECRET_KEY", None)
  193. if not key:
  194. raise RuntimeError(
  195. "JWT_SECRET_KEY or flask SECRET_KEY "
  196. "must be set when using symmetric "
  197. 'algorithm "{}"'.format(self.algorithm)
  198. )
  199. return key
  200. @property
  201. def _public_key(self) -> str:
  202. key = current_app.config["JWT_PUBLIC_KEY"]
  203. if not key:
  204. raise RuntimeError(
  205. "JWT_PUBLIC_KEY must be set to use "
  206. "asymmetric cryptography algorithm "
  207. '"{}"'.format(self.algorithm)
  208. )
  209. return key
  210. @property
  211. def _private_key(self) -> str:
  212. key = current_app.config["JWT_PRIVATE_KEY"]
  213. if not key:
  214. raise RuntimeError(
  215. "JWT_PRIVATE_KEY must be set to use "
  216. "asymmetric cryptography algorithm "
  217. '"{}"'.format(self.algorithm)
  218. )
  219. return key
  220. @property
  221. def cookie_max_age(self) -> Optional[int]:
  222. # Returns the appropiate value for max_age for flask set_cookies. If
  223. # session cookie is true, return None, otherwise return a number of
  224. # seconds 1 year in the future
  225. return None if self.session_cookie else 31540000 # 1 year
  226. @property
  227. def identity_claim_key(self) -> str:
  228. return current_app.config["JWT_IDENTITY_CLAIM"]
  229. @property
  230. def exempt_methods(self) -> Iterable[str]:
  231. return {"OPTIONS"}
  232. @property
  233. def error_msg_key(self) -> str:
  234. return current_app.config["JWT_ERROR_MESSAGE_KEY"]
  235. @property
  236. def json_encoder(self) -> Type[JSONEncoder]:
  237. return get_json_encoder(current_app)
  238. @property
  239. def decode_audience(self) -> Union[str, Iterable[str]]:
  240. return current_app.config["JWT_DECODE_AUDIENCE"]
  241. @property
  242. def encode_audience(self) -> Union[str, Iterable[str]]:
  243. return current_app.config["JWT_ENCODE_AUDIENCE"]
  244. @property
  245. def encode_issuer(self) -> str:
  246. return current_app.config["JWT_ENCODE_ISSUER"]
  247. @property
  248. def decode_issuer(self) -> str:
  249. return current_app.config["JWT_DECODE_ISSUER"]
  250. @property
  251. def leeway(self) -> int:
  252. return current_app.config["JWT_DECODE_LEEWAY"]
  253. @property
  254. def verify_sub(self) -> bool:
  255. return current_app.config["JWT_VERIFY_SUB"]
  256. @property
  257. def encode_nbf(self) -> bool:
  258. return current_app.config["JWT_ENCODE_NBF"]
  259. config = _Config()