resource.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth1.rfc5849.endpoints.resource
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module is an implementation of the resource protection provider logic of
  6. OAuth 1.0 RFC 5849.
  7. """
  8. from __future__ import absolute_import, unicode_literals
  9. import logging
  10. from .base import BaseEndpoint
  11. from .. import errors
  12. log = logging.getLogger(__name__)
  13. class ResourceEndpoint(BaseEndpoint):
  14. """An endpoint responsible for protecting resources.
  15. Typical use is to instantiate with a request validator and invoke the
  16. ``validate_protected_resource_request`` in a decorator around a view
  17. function. If the request is valid, invoke and return the response of the
  18. view. If invalid create and return an error response directly from the
  19. decorator.
  20. See :doc:`/oauth1/validator` for details on which validator methods to implement
  21. for this endpoint.
  22. An example decorator::
  23. from functools import wraps
  24. from your_validator import your_validator
  25. from oauthlib.oauth1 import ResourceEndpoint
  26. endpoint = ResourceEndpoint(your_validator)
  27. def require_oauth(realms=None):
  28. def decorator(f):
  29. @wraps(f)
  30. def wrapper(request, *args, **kwargs):
  31. v, r = provider.validate_protected_resource_request(
  32. request.url,
  33. http_method=request.method,
  34. body=request.data,
  35. headers=request.headers,
  36. realms=realms or [])
  37. if v:
  38. return f(*args, **kwargs)
  39. else:
  40. return abort(403)
  41. """
  42. def validate_protected_resource_request(self, uri, http_method='GET',
  43. body=None, headers=None, realms=None):
  44. """Create a request token response, with a new request token if valid.
  45. :param uri: The full URI of the token request.
  46. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
  47. :param body: The request body as a string.
  48. :param headers: The request headers as a dict.
  49. :param realms: A list of realms the resource is protected under.
  50. This will be supplied to the ``validate_realms``
  51. method of the request validator.
  52. :returns: A tuple of 2 elements.
  53. 1. True if valid, False otherwise.
  54. 2. An oauthlib.common.Request object.
  55. """
  56. try:
  57. request = self._create_request(uri, http_method, body, headers)
  58. except errors.OAuth1Error:
  59. return False, None
  60. try:
  61. self._check_transport_security(request)
  62. self._check_mandatory_parameters(request)
  63. except errors.OAuth1Error:
  64. return False, request
  65. if not request.resource_owner_key:
  66. return False, request
  67. if not self.request_validator.check_access_token(
  68. request.resource_owner_key):
  69. return False, request
  70. if not self.request_validator.validate_timestamp_and_nonce(
  71. request.client_key, request.timestamp, request.nonce, request,
  72. access_token=request.resource_owner_key):
  73. return False, request
  74. # The server SHOULD return a 401 (Unauthorized) status code when
  75. # receiving a request with invalid client credentials.
  76. # Note: This is postponed in order to avoid timing attacks, instead
  77. # a dummy client is assigned and used to maintain near constant
  78. # time request verification.
  79. #
  80. # Note that early exit would enable client enumeration
  81. valid_client = self.request_validator.validate_client_key(
  82. request.client_key, request)
  83. if not valid_client:
  84. request.client_key = self.request_validator.dummy_client
  85. # The server SHOULD return a 401 (Unauthorized) status code when
  86. # receiving a request with invalid or expired token.
  87. # Note: This is postponed in order to avoid timing attacks, instead
  88. # a dummy token is assigned and used to maintain near constant
  89. # time request verification.
  90. #
  91. # Note that early exit would enable resource owner enumeration
  92. valid_resource_owner = self.request_validator.validate_access_token(
  93. request.client_key, request.resource_owner_key, request)
  94. if not valid_resource_owner:
  95. request.resource_owner_key = self.request_validator.dummy_access_token
  96. # Note that `realm`_ is only used in authorization headers and how
  97. # it should be interepreted is not included in the OAuth spec.
  98. # However they could be seen as a scope or realm to which the
  99. # client has access and as such every client should be checked
  100. # to ensure it is authorized access to that scope or realm.
  101. # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2
  102. #
  103. # Note that early exit would enable client realm access enumeration.
  104. #
  105. # The require_realm indicates this is the first step in the OAuth
  106. # workflow where a client requests access to a specific realm.
  107. # This first step (obtaining request token) need not require a realm
  108. # and can then be identified by checking the require_resource_owner
  109. # flag and abscence of realm.
  110. #
  111. # Clients obtaining an access token will not supply a realm and it will
  112. # not be checked. Instead the previously requested realm should be
  113. # transferred from the request token to the access token.
  114. #
  115. # Access to protected resources will always validate the realm but note
  116. # that the realm is now tied to the access token and not provided by
  117. # the client.
  118. valid_realm = self.request_validator.validate_realms(request.client_key,
  119. request.resource_owner_key, request, uri=request.uri,
  120. realms=realms)
  121. valid_signature = self._check_signature(request)
  122. # log the results to the validator_log
  123. # this lets us handle internal reporting and analysis
  124. request.validator_log['client'] = valid_client
  125. request.validator_log['resource_owner'] = valid_resource_owner
  126. request.validator_log['realm'] = valid_realm
  127. request.validator_log['signature'] = valid_signature
  128. # We delay checking validity until the very end, using dummy values for
  129. # calculations and fetching secrets/keys to ensure the flow of every
  130. # request remains almost identical regardless of whether valid values
  131. # have been supplied. This ensures near constant time execution and
  132. # prevents malicious users from guessing sensitive information
  133. v = all((valid_client, valid_resource_owner, valid_realm,
  134. valid_signature))
  135. if not v:
  136. log.info("[Failure] request verification failed.")
  137. log.info("Valid client: %s", valid_client)
  138. log.info("Valid token: %s", valid_resource_owner)
  139. log.info("Valid realm: %s", valid_realm)
  140. log.info("Valid signature: %s", valid_signature)
  141. return v, request