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. from __future__ import absolute_import, unicode_literals
  11. import logging
  12. from oauthlib.common import urlencode
  13. from .base import BaseEndpoint
  14. from .. import errors
  15. log = logging.getLogger(__name__)
  16. class RequestTokenEndpoint(BaseEndpoint):
  17. """An endpoint responsible for providing OAuth 1 request tokens.
  18. Typical use is to instantiate with a request validator and invoke the
  19. ``create_request_token_response`` from a view function. The tuple returned
  20. has all information necessary (body, status, headers) to quickly form
  21. and return a proper response. See :doc:`/oauth1/validator` for details on which
  22. validator methods to implement for this endpoint.
  23. """
  24. def create_request_token(self, request, credentials):
  25. """Create and save a new request token.
  26. :param request: An oauthlib.common.Request object.
  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: An oauthlib.common.Request object.
  94. :raises: OAuth1Error if the request is invalid.
  95. :returns: A tuple of 2 elements.
  96. 1. The validation result (True or False).
  97. 2. The request object.
  98. """
  99. self._check_transport_security(request)
  100. self._check_mandatory_parameters(request)
  101. if request.realm:
  102. request.realms = request.realm.split(' ')
  103. else:
  104. request.realms = self.request_validator.get_default_realms(
  105. request.client_key, request)
  106. if not self.request_validator.check_realms(request.realms):
  107. raise errors.InvalidRequestError(
  108. description='Invalid realm %s. Allowed are %r.' % (
  109. request.realms, self.request_validator.realms))
  110. if not request.redirect_uri:
  111. raise errors.InvalidRequestError(
  112. description='Missing callback URI.')
  113. if not self.request_validator.validate_timestamp_and_nonce(
  114. request.client_key, request.timestamp, request.nonce, request,
  115. request_token=request.resource_owner_key):
  116. return False, request
  117. # The server SHOULD return a 401 (Unauthorized) status code when
  118. # receiving a request with invalid client credentials.
  119. # Note: This is postponed in order to avoid timing attacks, instead
  120. # a dummy client is assigned and used to maintain near constant
  121. # time request verification.
  122. #
  123. # Note that early exit would enable client enumeration
  124. valid_client = self.request_validator.validate_client_key(
  125. request.client_key, request)
  126. if not valid_client:
  127. request.client_key = self.request_validator.dummy_client
  128. # Note that `realm`_ is only used in authorization headers and how
  129. # it should be interepreted is not included in the OAuth spec.
  130. # However they could be seen as a scope or realm to which the
  131. # client has access and as such every client should be checked
  132. # to ensure it is authorized access to that scope or realm.
  133. # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2
  134. #
  135. # Note that early exit would enable client realm access enumeration.
  136. #
  137. # The require_realm indicates this is the first step in the OAuth
  138. # workflow where a client requests access to a specific realm.
  139. # This first step (obtaining request token) need not require a realm
  140. # and can then be identified by checking the require_resource_owner
  141. # flag and abscence of realm.
  142. #
  143. # Clients obtaining an access token will not supply a realm and it will
  144. # not be checked. Instead the previously requested realm should be
  145. # transferred from the request token to the access token.
  146. #
  147. # Access to protected resources will always validate the realm but note
  148. # that the realm is now tied to the access token and not provided by
  149. # the client.
  150. valid_realm = self.request_validator.validate_requested_realms(
  151. request.client_key, request.realms, request)
  152. # Callback is normally never required, except for requests for
  153. # a Temporary Credential as described in `Section 2.1`_
  154. # .._`Section 2.1`: http://tools.ietf.org/html/rfc5849#section-2.1
  155. valid_redirect = self.request_validator.validate_redirect_uri(
  156. request.client_key, request.redirect_uri, request)
  157. if not request.redirect_uri:
  158. raise NotImplementedError('Redirect URI must either be provided '
  159. 'or set to a default during validation.')
  160. valid_signature = self._check_signature(request)
  161. # log the results to the validator_log
  162. # this lets us handle internal reporting and analysis
  163. request.validator_log['client'] = valid_client
  164. request.validator_log['realm'] = valid_realm
  165. request.validator_log['callback'] = valid_redirect
  166. request.validator_log['signature'] = valid_signature
  167. # We delay checking validity until the very end, using dummy values for
  168. # calculations and fetching secrets/keys to ensure the flow of every
  169. # request remains almost identical regardless of whether valid values
  170. # have been supplied. This ensures near constant time execution and
  171. # prevents malicious users from guessing sensitive information
  172. v = all((valid_client, valid_realm, valid_redirect, valid_signature))
  173. if not v:
  174. log.info("[Failure] request verification failed.")
  175. log.info("Valid client: %s.", valid_client)
  176. log.info("Valid realm: %s.", valid_realm)
  177. log.info("Valid callback: %s.", valid_redirect)
  178. log.info("Valid signature: %s.", valid_signature)
  179. return v, request