request_validator.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth2.rfc6749.grant_types
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. """
  6. from __future__ import unicode_literals, absolute_import
  7. import logging
  8. log = logging.getLogger(__name__)
  9. class RequestValidator(object):
  10. def client_authentication_required(self, request, *args, **kwargs):
  11. """Determine if client authentication is required for current request.
  12. According to the rfc6749, client authentication is required in the following cases:
  13. - Resource Owner Password Credentials Grant, when Client type is Confidential or when
  14. Client was issued client credentials or whenever Client provided client
  15. authentication, see `Section 4.3.2`_.
  16. - Authorization Code Grant, when Client type is Confidential or when Client was issued
  17. client credentials or whenever Client provided client authentication,
  18. see `Section 4.1.3`_.
  19. - Refresh Token Grant, when Client type is Confidential or when Client was issued
  20. client credentials or whenever Client provided client authentication, see
  21. `Section 6`_
  22. :param request: oauthlib.common.Request
  23. :rtype: True or False
  24. Method is used by:
  25. - Authorization Code Grant
  26. - Resource Owner Password Credentials Grant
  27. - Refresh Token Grant
  28. .. _`Section 4.3.2`: http://tools.ietf.org/html/rfc6749#section-4.3.2
  29. .. _`Section 4.1.3`: http://tools.ietf.org/html/rfc6749#section-4.1.3
  30. .. _`Section 6`: http://tools.ietf.org/html/rfc6749#section-6
  31. """
  32. return True
  33. def authenticate_client(self, request, *args, **kwargs):
  34. """Authenticate client through means outside the OAuth 2 spec.
  35. Means of authentication is negotiated beforehand and may for example
  36. be `HTTP Basic Authentication Scheme`_ which utilizes the Authorization
  37. header.
  38. Headers may be accesses through request.headers and parameters found in
  39. both body and query can be obtained by direct attribute access, i.e.
  40. request.client_id for client_id in the URL query.
  41. :param request: oauthlib.common.Request
  42. :rtype: True or False
  43. Method is used by:
  44. - Authorization Code Grant
  45. - Resource Owner Password Credentials Grant (may be disabled)
  46. - Client Credentials Grant
  47. - Refresh Token Grant
  48. .. _`HTTP Basic Authentication Scheme`: http://tools.ietf.org/html/rfc1945#section-11.1
  49. """
  50. raise NotImplementedError('Subclasses must implement this method.')
  51. def authenticate_client_id(self, client_id, request, *args, **kwargs):
  52. """Ensure client_id belong to a non-confidential client.
  53. A non-confidential client is one that is not required to authenticate
  54. through other means, such as using HTTP Basic.
  55. Note, while not strictly necessary it can often be very convenient
  56. to set request.client to the client object associated with the
  57. given client_id.
  58. :param request: oauthlib.common.Request
  59. :rtype: True or False
  60. Method is used by:
  61. - Authorization Code Grant
  62. """
  63. raise NotImplementedError('Subclasses must implement this method.')
  64. def confirm_redirect_uri(self, client_id, code, redirect_uri, client,
  65. *args, **kwargs):
  66. """Ensure that the authorization process represented by this authorization
  67. code began with this 'redirect_uri'.
  68. If the client specifies a redirect_uri when obtaining code then that
  69. redirect URI must be bound to the code and verified equal in this
  70. method, according to RFC 6749 section 4.1.3. Do not compare against
  71. the client's allowed redirect URIs, but against the URI used when the
  72. code was saved.
  73. :param client_id: Unicode client identifier
  74. :param code: Unicode authorization_code.
  75. :param redirect_uri: Unicode absolute URI
  76. :param client: Client object set by you, see authenticate_client.
  77. :param request: The HTTP Request (oauthlib.common.Request)
  78. :rtype: True or False
  79. Method is used by:
  80. - Authorization Code Grant (during token request)
  81. """
  82. raise NotImplementedError('Subclasses must implement this method.')
  83. def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
  84. """Get the default redirect URI for the client.
  85. :param client_id: Unicode client identifier
  86. :param request: The HTTP Request (oauthlib.common.Request)
  87. :rtype: The default redirect URI for the client
  88. Method is used by:
  89. - Authorization Code Grant
  90. - Implicit Grant
  91. """
  92. raise NotImplementedError('Subclasses must implement this method.')
  93. def get_default_scopes(self, client_id, request, *args, **kwargs):
  94. """Get the default scopes for the client.
  95. :param client_id: Unicode client identifier
  96. :param request: The HTTP Request (oauthlib.common.Request)
  97. :rtype: List of default scopes
  98. Method is used by all core grant types:
  99. - Authorization Code Grant
  100. - Implicit Grant
  101. - Resource Owner Password Credentials Grant
  102. - Client Credentials grant
  103. """
  104. raise NotImplementedError('Subclasses must implement this method.')
  105. def get_original_scopes(self, refresh_token, request, *args, **kwargs):
  106. """Get the list of scopes associated with the refresh token.
  107. :param refresh_token: Unicode refresh token
  108. :param request: The HTTP Request (oauthlib.common.Request)
  109. :rtype: List of scopes.
  110. Method is used by:
  111. - Refresh token grant
  112. """
  113. raise NotImplementedError('Subclasses must implement this method.')
  114. def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs):
  115. """Check if requested scopes are within a scope of the refresh token.
  116. When access tokens are refreshed the scope of the new token
  117. needs to be within the scope of the original token. This is
  118. ensured by checking that all requested scopes strings are on
  119. the list returned by the get_original_scopes. If this check
  120. fails, is_within_original_scope is called. The method can be
  121. used in situations where returning all valid scopes from the
  122. get_original_scopes is not practical.
  123. :param request_scopes: A list of scopes that were requested by client
  124. :param refresh_token: Unicode refresh_token
  125. :param request: The HTTP Request (oauthlib.common.Request)
  126. :rtype: True or False
  127. Method is used by:
  128. - Refresh token grant
  129. """
  130. return False
  131. def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
  132. """Invalidate an authorization code after use.
  133. :param client_id: Unicode client identifier
  134. :param code: The authorization code grant (request.code).
  135. :param request: The HTTP Request (oauthlib.common.Request)
  136. Method is used by:
  137. - Authorization Code Grant
  138. """
  139. raise NotImplementedError('Subclasses must implement this method.')
  140. def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
  141. """Revoke an access or refresh token.
  142. :param token: The token string.
  143. :param token_type_hint: access_token or refresh_token.
  144. :param request: The HTTP Request (oauthlib.common.Request)
  145. Method is used by:
  146. - Revocation Endpoint
  147. """
  148. raise NotImplementedError('Subclasses must implement this method.')
  149. def rotate_refresh_token(self, request):
  150. """Determine whether to rotate the refresh token. Default, yes.
  151. When access tokens are refreshed the old refresh token can be kept
  152. or replaced with a new one (rotated). Return True to rotate and
  153. and False for keeping original.
  154. :param request: oauthlib.common.Request
  155. :rtype: True or False
  156. Method is used by:
  157. - Refresh Token Grant
  158. """
  159. return True
  160. def save_authorization_code(self, client_id, code, request, *args, **kwargs):
  161. """Persist the authorization_code.
  162. The code should at minimum be stored with:
  163. - the client_id (client_id)
  164. - the redirect URI used (request.redirect_uri)
  165. - a resource owner / user (request.user)
  166. - the authorized scopes (request.scopes)
  167. - the client state, if given (code.get('state'))
  168. The 'code' argument is actually a dictionary, containing at least a
  169. 'code' key with the actual authorization code:
  170. {'code': 'sdf345jsdf0934f'}
  171. It may also have a 'state' key containing a nonce for the client, if it
  172. chose to send one. That value should be saved and used in
  173. 'validate_code'.
  174. It may also have a 'claims' parameter which, when present, will be a dict
  175. deserialized from JSON as described at
  176. http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
  177. This value should be saved in this method and used again in 'validate_code'.
  178. :param client_id: Unicode client identifier
  179. :param code: A dict of the authorization code grant and, optionally, state.
  180. :param request: The HTTP Request (oauthlib.common.Request)
  181. Method is used by:
  182. - Authorization Code Grant
  183. """
  184. raise NotImplementedError('Subclasses must implement this method.')
  185. def save_token(self, token, request, *args, **kwargs):
  186. """Persist the token with a token type specific method.
  187. Currently, only save_bearer_token is supported.
  188. """
  189. return self.save_bearer_token(token, request, *args, **kwargs)
  190. def save_bearer_token(self, token, request, *args, **kwargs):
  191. """Persist the Bearer token.
  192. The Bearer token should at minimum be associated with:
  193. - a client and it's client_id, if available
  194. - a resource owner / user (request.user)
  195. - authorized scopes (request.scopes)
  196. - an expiration time
  197. - a refresh token, if issued
  198. - a claims document, if present in request.claims
  199. The Bearer token dict may hold a number of items::
  200. {
  201. 'token_type': 'Bearer',
  202. 'access_token': 'askfjh234as9sd8',
  203. 'expires_in': 3600,
  204. 'scope': 'string of space separated authorized scopes',
  205. 'refresh_token': '23sdf876234', # if issued
  206. 'state': 'given_by_client', # if supplied by client
  207. }
  208. Note that while "scope" is a string-separated list of authorized scopes,
  209. the original list is still available in request.scopes
  210. Also note that if an Authorization Code grant request included a valid claims
  211. parameter (for OpenID Connect) then the request.claims property will contain
  212. the claims dict, which should be saved for later use when generating the
  213. id_token and/or UserInfo response content.
  214. :param client_id: Unicode client identifier
  215. :param token: A Bearer token dict
  216. :param request: The HTTP Request (oauthlib.common.Request)
  217. :rtype: The default redirect URI for the client
  218. Method is used by all core grant types issuing Bearer tokens:
  219. - Authorization Code Grant
  220. - Implicit Grant
  221. - Resource Owner Password Credentials Grant (might not associate a client)
  222. - Client Credentials grant
  223. """
  224. raise NotImplementedError('Subclasses must implement this method.')
  225. def get_id_token(self, token, token_handler, request):
  226. """
  227. In the OpenID Connect workflows when an ID Token is requested this method is called.
  228. Subclasses should implement the construction, signing and optional encryption of the
  229. ID Token as described in the OpenID Connect spec.
  230. In addition to the standard OAuth2 request properties, the request may also contain
  231. these OIDC specific properties which are useful to this method:
  232. - nonce, if workflow is implicit or hybrid and it was provided
  233. - claims, if provided to the original Authorization Code request
  234. The token parameter is a dict which may contain an ``access_token`` entry, in which
  235. case the resulting ID Token *should* include a calculated ``at_hash`` claim.
  236. Similarly, when the request parameter has a ``code`` property defined, the ID Token
  237. *should* include a calculated ``c_hash`` claim.
  238. http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_)
  239. .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  240. .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken
  241. .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
  242. :param token: A Bearer token dict
  243. :param token_handler: the token handler (BearerToken class)
  244. :param request: the HTTP Request (oauthlib.common.Request)
  245. :return: The ID Token (a JWS signed JWT)
  246. """
  247. # the request.scope should be used by the get_id_token() method to determine which claims to include in the resulting id_token
  248. raise NotImplementedError('Subclasses must implement this method.')
  249. def validate_bearer_token(self, token, scopes, request):
  250. """Ensure the Bearer token is valid and authorized access to scopes.
  251. :param token: A string of random characters.
  252. :param scopes: A list of scopes associated with the protected resource.
  253. :param request: The HTTP Request (oauthlib.common.Request)
  254. A key to OAuth 2 security and restricting impact of leaked tokens is
  255. the short expiration time of tokens, *always ensure the token has not
  256. expired!*.
  257. Two different approaches to scope validation:
  258. 1) all(scopes). The token must be authorized access to all scopes
  259. associated with the resource. For example, the
  260. token has access to ``read-only`` and ``images``,
  261. thus the client can view images but not upload new.
  262. Allows for fine grained access control through
  263. combining various scopes.
  264. 2) any(scopes). The token must be authorized access to one of the
  265. scopes associated with the resource. For example,
  266. token has access to ``read-only-images``.
  267. Allows for fine grained, although arguably less
  268. convenient, access control.
  269. A powerful way to use scopes would mimic UNIX ACLs and see a scope
  270. as a group with certain privileges. For a restful API these might
  271. map to HTTP verbs instead of read, write and execute.
  272. Note, the request.user attribute can be set to the resource owner
  273. associated with this token. Similarly the request.client and
  274. request.scopes attribute can be set to associated client object
  275. and authorized scopes. If you then use a decorator such as the
  276. one provided for django these attributes will be made available
  277. in all protected views as keyword arguments.
  278. :param token: Unicode Bearer token
  279. :param scopes: List of scopes (defined by you)
  280. :param request: The HTTP Request (oauthlib.common.Request)
  281. :rtype: True or False
  282. Method is indirectly used by all core Bearer token issuing grant types:
  283. - Authorization Code Grant
  284. - Implicit Grant
  285. - Resource Owner Password Credentials Grant
  286. - Client Credentials Grant
  287. """
  288. raise NotImplementedError('Subclasses must implement this method.')
  289. def validate_client_id(self, client_id, request, *args, **kwargs):
  290. """Ensure client_id belong to a valid and active client.
  291. Note, while not strictly necessary it can often be very convenient
  292. to set request.client to the client object associated with the
  293. given client_id.
  294. :param request: oauthlib.common.Request
  295. :rtype: True or False
  296. Method is used by:
  297. - Authorization Code Grant
  298. - Implicit Grant
  299. """
  300. raise NotImplementedError('Subclasses must implement this method.')
  301. def validate_code(self, client_id, code, client, request, *args, **kwargs):
  302. """Verify that the authorization_code is valid and assigned to the given
  303. client.
  304. Before returning true, set the following based on the information stored
  305. with the code in 'save_authorization_code':
  306. - request.user
  307. - request.state (if given)
  308. - request.scopes
  309. - request.claims (if given)
  310. OBS! The request.user attribute should be set to the resource owner
  311. associated with this authorization code. Similarly request.scopes
  312. must also be set.
  313. The request.claims property, if it was given, should assigned a dict.
  314. :param client_id: Unicode client identifier
  315. :param code: Unicode authorization code
  316. :param client: Client object set by you, see authenticate_client.
  317. :param request: The HTTP Request (oauthlib.common.Request)
  318. :rtype: True or False
  319. Method is used by:
  320. - Authorization Code Grant
  321. """
  322. raise NotImplementedError('Subclasses must implement this method.')
  323. def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
  324. """Ensure client is authorized to use the grant_type requested.
  325. :param client_id: Unicode client identifier
  326. :param grant_type: Unicode grant type, i.e. authorization_code, password.
  327. :param client: Client object set by you, see authenticate_client.
  328. :param request: The HTTP Request (oauthlib.common.Request)
  329. :rtype: True or False
  330. Method is used by:
  331. - Authorization Code Grant
  332. - Resource Owner Password Credentials Grant
  333. - Client Credentials Grant
  334. - Refresh Token Grant
  335. """
  336. raise NotImplementedError('Subclasses must implement this method.')
  337. def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
  338. """Ensure client is authorized to redirect to the redirect_uri requested.
  339. All clients should register the absolute URIs of all URIs they intend
  340. to redirect to. The registration is outside of the scope of oauthlib.
  341. :param client_id: Unicode client identifier
  342. :param redirect_uri: Unicode absolute URI
  343. :param request: The HTTP Request (oauthlib.common.Request)
  344. :rtype: True or False
  345. Method is used by:
  346. - Authorization Code Grant
  347. - Implicit Grant
  348. """
  349. raise NotImplementedError('Subclasses must implement this method.')
  350. def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
  351. """Ensure the Bearer token is valid and authorized access to scopes.
  352. OBS! The request.user attribute should be set to the resource owner
  353. associated with this refresh token.
  354. :param refresh_token: Unicode refresh token
  355. :param client: Client object set by you, see authenticate_client.
  356. :param request: The HTTP Request (oauthlib.common.Request)
  357. :rtype: True or False
  358. Method is used by:
  359. - Authorization Code Grant (indirectly by issuing refresh tokens)
  360. - Resource Owner Password Credentials Grant (also indirectly)
  361. - Refresh Token Grant
  362. """
  363. raise NotImplementedError('Subclasses must implement this method.')
  364. def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
  365. """Ensure client is authorized to use the response_type requested.
  366. :param client_id: Unicode client identifier
  367. :param response_type: Unicode response type, i.e. code, token.
  368. :param client: Client object set by you, see authenticate_client.
  369. :param request: The HTTP Request (oauthlib.common.Request)
  370. :rtype: True or False
  371. Method is used by:
  372. - Authorization Code Grant
  373. - Implicit Grant
  374. """
  375. raise NotImplementedError('Subclasses must implement this method.')
  376. def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
  377. """Ensure the client is authorized access to requested scopes.
  378. :param client_id: Unicode client identifier
  379. :param scopes: List of scopes (defined by you)
  380. :param client: Client object set by you, see authenticate_client.
  381. :param request: The HTTP Request (oauthlib.common.Request)
  382. :rtype: True or False
  383. Method is used by all core grant types:
  384. - Authorization Code Grant
  385. - Implicit Grant
  386. - Resource Owner Password Credentials Grant
  387. - Client Credentials Grant
  388. """
  389. raise NotImplementedError('Subclasses must implement this method.')
  390. def validate_silent_authorization(self, request):
  391. """Ensure the logged in user has authorized silent OpenID authorization.
  392. Silent OpenID authorization allows access tokens and id tokens to be
  393. granted to clients without any user prompt or interaction.
  394. :param request: The HTTP Request (oauthlib.common.Request)
  395. :rtype: True or False
  396. Method is used by:
  397. - OpenIDConnectAuthCode
  398. - OpenIDConnectImplicit
  399. - OpenIDConnectHybrid
  400. """
  401. raise NotImplementedError('Subclasses must implement this method.')
  402. def validate_silent_login(self, request):
  403. """Ensure session user has authorized silent OpenID login.
  404. If no user is logged in or has not authorized silent login, this
  405. method should return False.
  406. If the user is logged in but associated with multiple accounts and
  407. not selected which one to link to the token then this method should
  408. raise an oauthlib.oauth2.AccountSelectionRequired error.
  409. :param request: The HTTP Request (oauthlib.common.Request)
  410. :rtype: True or False
  411. Method is used by:
  412. - OpenIDConnectAuthCode
  413. - OpenIDConnectImplicit
  414. - OpenIDConnectHybrid
  415. """
  416. raise NotImplementedError('Subclasses must implement this method.')
  417. def validate_user(self, username, password, client, request, *args, **kwargs):
  418. """Ensure the username and password is valid.
  419. OBS! The validation should also set the user attribute of the request
  420. to a valid resource owner, i.e. request.user = username or similar. If
  421. not set you will be unable to associate a token with a user in the
  422. persistance method used (commonly, save_bearer_token).
  423. :param username: Unicode username
  424. :param password: Unicode password
  425. :param client: Client object set by you, see authenticate_client.
  426. :param request: The HTTP Request (oauthlib.common.Request)
  427. :rtype: True or False
  428. Method is used by:
  429. - Resource Owner Password Credentials Grant
  430. """
  431. raise NotImplementedError('Subclasses must implement this method.')
  432. def validate_user_match(self, id_token_hint, scopes, claims, request):
  433. """Ensure client supplied user id hint matches session user.
  434. If the sub claim or id_token_hint is supplied then the session
  435. user must match the given ID.
  436. :param id_token_hint: User identifier string.
  437. :param scopes: List of OAuth 2 scopes and OpenID claims (strings).
  438. :param claims: OpenID Connect claims dict.
  439. :param request: The HTTP Request (oauthlib.common.Request)
  440. :rtype: True or False
  441. Method is used by:
  442. - OpenIDConnectAuthCode
  443. - OpenIDConnectImplicit
  444. - OpenIDConnectHybrid
  445. """
  446. raise NotImplementedError('Subclasses must implement this method.')