request_token.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth1.rfc5849.endpoints.request_token
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module is an implementation of the request token provider logic of
  6. OAuth 1.0 RFC 5849. It validates the correctness of request token requests,
  7. creates and persists tokens as well as create the proper response to be
  8. returned to the client.
  9. """
  10. import logging
  11. from oauthlib.common import urlencode
  12. from .. import errors
  13. from .base import BaseEndpoint
  14. log = logging.getLogger(__name__)
  15. class RequestTokenEndpoint(BaseEndpoint):
  16. """An endpoint responsible for providing OAuth 1 request tokens.
  17. Typical use is to instantiate with a request validator and invoke the
  18. ``create_request_token_response`` from a view function. The tuple returned
  19. has all information necessary (body, status, headers) to quickly form
  20. and return a proper response. See :doc:`/oauth1/validator` for details on which
  21. validator methods to implement for this endpoint.
  22. """
  23. def create_request_token(self, request, credentials):
  24. """Create and save a new request token.
  25. :param request: OAuthlib request.
  26. :type request: oauthlib.common.Request
  27. :param credentials: A dict of extra token credentials.
  28. :returns: The token as an urlencoded string.
  29. """
  30. token = {
  31. 'oauth_token': self.token_generator(),
  32. 'oauth_token_secret': self.token_generator(),
  33. 'oauth_callback_confirmed': 'true'
  34. }
  35. token.update(credentials)
  36. self.request_validator.save_request_token(token, request)
  37. return urlencode(token.items())
  38. def create_request_token_response(self, uri, http_method='GET', body=None,
  39. headers=None, credentials=None):
  40. """Create a request token response, with a new request token if valid.
  41. :param uri: The full URI of the token request.
  42. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
  43. :param body: The request body as a string.
  44. :param headers: The request headers as a dict.
  45. :param credentials: A list of extra credentials to include in the token.
  46. :returns: A tuple of 3 elements.
  47. 1. A dict of headers to set on the response.
  48. 2. The response body as a string.
  49. 3. The response status code as an integer.
  50. An example of a valid request::
  51. >>> from your_validator import your_validator
  52. >>> from oauthlib.oauth1 import RequestTokenEndpoint
  53. >>> endpoint = RequestTokenEndpoint(your_validator)
  54. >>> h, b, s = endpoint.create_request_token_response(
  55. ... 'https://your.provider/request_token?foo=bar',
  56. ... headers={
  57. ... 'Authorization': 'OAuth realm=movies user, oauth_....'
  58. ... },
  59. ... credentials={
  60. ... 'my_specific': 'argument',
  61. ... })
  62. >>> h
  63. {'Content-Type': 'application/x-www-form-urlencoded'}
  64. >>> b
  65. 'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_callback_confirmed=true&my_specific=argument'
  66. >>> s
  67. 200
  68. An response to invalid request would have a different body and status::
  69. >>> b
  70. 'error=invalid_request&description=missing+callback+uri'
  71. >>> s
  72. 400
  73. The same goes for an an unauthorized request:
  74. >>> b
  75. ''
  76. >>> s
  77. 401
  78. """
  79. resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  80. try:
  81. request = self._create_request(uri, http_method, body, headers)
  82. valid, processed_request = self.validate_request_token_request(
  83. request)
  84. if valid:
  85. token = self.create_request_token(request, credentials or {})
  86. return resp_headers, token, 200
  87. else:
  88. return {}, None, 401
  89. except errors.OAuth1Error as e:
  90. return resp_headers, e.urlencoded, e.status_code
  91. def validate_request_token_request(self, request):
  92. """Validate a request token request.
  93. :param request: OAuthlib request.
  94. :type request: oauthlib.common.Request
  95. :raises: OAuth1Error if the request is invalid.
  96. :returns: A tuple of 2 elements.
  97. 1. The validation result (True or False).
  98. 2. The request object.
  99. """
  100. self._check_transport_security(request)
  101. self._check_mandatory_parameters(request)
  102. if request.realm:
  103. request.realms = request.realm.split(' ')
  104. else:
  105. request.realms = self.request_validator.get_default_realms(
  106. request.client_key, request)
  107. if not self.request_validator.check_realms(request.realms):
  108. raise errors.InvalidRequestError(
  109. description='Invalid realm {}. Allowed are {!r}.'.format(
  110. request.realms, self.request_validator.realms))
  111. if not request.redirect_uri:
  112. raise errors.InvalidRequestError(
  113. description='Missing callback URI.')
  114. if not self.request_validator.validate_timestamp_and_nonce(
  115. request.client_key, request.timestamp, request.nonce, request,
  116. request_token=request.resource_owner_key):
  117. return False, request
  118. # The server SHOULD return a 401 (Unauthorized) status code when
  119. # receiving a request with invalid client credentials.
  120. # Note: This is postponed in order to avoid timing attacks, instead
  121. # a dummy client is assigned and used to maintain near constant
  122. # time request verification.
  123. #
  124. # Note that early exit would enable client enumeration
  125. valid_client = self.request_validator.validate_client_key(
  126. request.client_key, request)
  127. if not valid_client:
  128. request.client_key = self.request_validator.dummy_client
  129. # Note that `realm`_ is only used in authorization headers and how
  130. # it should be interpreted is not included in the OAuth spec.
  131. # However they could be seen as a scope or realm to which the
  132. # client has access and as such every client should be checked
  133. # to ensure it is authorized access to that scope or realm.
  134. # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2
  135. #
  136. # Note that early exit would enable client realm access enumeration.
  137. #
  138. # The require_realm indicates this is the first step in the OAuth
  139. # workflow where a client requests access to a specific realm.
  140. # This first step (obtaining request token) need not require a realm
  141. # and can then be identified by checking the require_resource_owner
  142. # flag and absence of realm.
  143. #
  144. # Clients obtaining an access token will not supply a realm and it will
  145. # not be checked. Instead the previously requested realm should be
  146. # transferred from the request token to the access token.
  147. #
  148. # Access to protected resources will always validate the realm but note
  149. # that the realm is now tied to the access token and not provided by
  150. # the client.
  151. valid_realm = self.request_validator.validate_requested_realms(
  152. request.client_key, request.realms, request)
  153. # Callback is normally never required, except for requests for
  154. # a Temporary Credential as described in `Section 2.1`_
  155. # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1
  156. valid_redirect = self.request_validator.validate_redirect_uri(
  157. request.client_key, request.redirect_uri, request)
  158. if not request.redirect_uri:
  159. raise NotImplementedError('Redirect URI must either be provided '
  160. 'or set to a default during validation.')
  161. valid_signature = self._check_signature(request)
  162. # log the results to the validator_log
  163. # this lets us handle internal reporting and analysis
  164. request.validator_log['client'] = valid_client
  165. request.validator_log['realm'] = valid_realm
  166. request.validator_log['callback'] = valid_redirect
  167. request.validator_log['signature'] = valid_signature
  168. # We delay checking validity until the very end, using dummy values for
  169. # calculations and fetching secrets/keys to ensure the flow of every
  170. # request remains almost identical regardless of whether valid values
  171. # have been supplied. This ensures near constant time execution and
  172. # prevents malicious users from guessing sensitive information
  173. v = all((valid_client, valid_realm, valid_redirect, valid_signature))
  174. if not v:
  175. log.info("[Failure] request verification failed.")
  176. log.info("Valid client: %s.", valid_client)
  177. log.info("Valid realm: %s.", valid_realm)
  178. log.info("Valid callback: %s.", valid_redirect)
  179. log.info("Valid signature: %s.", valid_signature)
  180. return v, request