parameters.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth2.rfc6749.parameters
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module contains methods related to `Section 4`_ of the OAuth 2 RFC.
  6. .. _`Section 4`: http://tools.ietf.org/html/rfc6749#section-4
  7. """
  8. from __future__ import absolute_import, unicode_literals
  9. import json
  10. import os
  11. import time
  12. try:
  13. import urlparse
  14. except ImportError:
  15. import urllib.parse as urlparse
  16. from oauthlib.common import add_params_to_uri, add_params_to_qs, unicode_type
  17. from oauthlib.signals import scope_changed
  18. from .errors import raise_from_error, MissingTokenError, MissingTokenTypeError
  19. from .errors import MismatchingStateError, MissingCodeError
  20. from .errors import InsecureTransportError
  21. from .tokens import OAuth2Token
  22. from .utils import list_to_scope, scope_to_list, is_secure_transport
  23. def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
  24. scope=None, state=None, **kwargs):
  25. """Prepare the authorization grant request URI.
  26. The client constructs the request URI by adding the following
  27. parameters to the query component of the authorization endpoint URI
  28. using the ``application/x-www-form-urlencoded`` format as defined by
  29. [`W3C.REC-html401-19991224`_]:
  30. :param response_type: To indicate which OAuth 2 grant/flow is required,
  31. "code" and "token".
  32. :param client_id: The client identifier as described in `Section 2.2`_.
  33. :param redirect_uri: The client provided URI to redirect back to after
  34. authorization as described in `Section 3.1.2`_.
  35. :param scope: The scope of the access request as described by
  36. `Section 3.3`_.
  37. :param state: An opaque value used by the client to maintain
  38. state between the request and callback. The authorization
  39. server includes this value when redirecting the user-agent
  40. back to the client. The parameter SHOULD be used for
  41. preventing cross-site request forgery as described in
  42. `Section 10.12`_.
  43. :param kwargs: Extra arguments to embed in the grant/authorization URL.
  44. An example of an authorization code grant authorization URL:
  45. .. code-block:: http
  46. GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
  47. &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
  48. Host: server.example.com
  49. .. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224
  50. .. _`Section 2.2`: http://tools.ietf.org/html/rfc6749#section-2.2
  51. .. _`Section 3.1.2`: http://tools.ietf.org/html/rfc6749#section-3.1.2
  52. .. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3
  53. .. _`section 10.12`: http://tools.ietf.org/html/rfc6749#section-10.12
  54. """
  55. if not is_secure_transport(uri):
  56. raise InsecureTransportError()
  57. params = [(('response_type', response_type)),
  58. (('client_id', client_id))]
  59. if redirect_uri:
  60. params.append(('redirect_uri', redirect_uri))
  61. if scope:
  62. params.append(('scope', list_to_scope(scope)))
  63. if state:
  64. params.append(('state', state))
  65. for k in kwargs:
  66. if kwargs[k]:
  67. params.append((unicode_type(k), kwargs[k]))
  68. return add_params_to_uri(uri, params)
  69. def prepare_token_request(grant_type, body='', **kwargs):
  70. """Prepare the access token request.
  71. The client makes a request to the token endpoint by adding the
  72. following parameters using the ``application/x-www-form-urlencoded``
  73. format in the HTTP request entity-body:
  74. :param grant_type: To indicate grant type being used, i.e. "password",
  75. "authorization_code" or "client_credentials".
  76. :param body: Existing request body to embed parameters in.
  77. :param code: If using authorization code grant, pass the previously
  78. obtained authorization code as the ``code`` argument.
  79. :param redirect_uri: If the "redirect_uri" parameter was included in the
  80. authorization request as described in
  81. `Section 4.1.1`_, and their values MUST be identical.
  82. :param kwargs: Extra arguments to embed in the request body.
  83. An example of an authorization code token request body:
  84. .. code-block:: http
  85. grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
  86. &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
  87. .. _`Section 4.1.1`: http://tools.ietf.org/html/rfc6749#section-4.1.1
  88. """
  89. params = [('grant_type', grant_type)]
  90. if 'scope' in kwargs:
  91. kwargs['scope'] = list_to_scope(kwargs['scope'])
  92. for k in kwargs:
  93. if kwargs[k]:
  94. params.append((unicode_type(k), kwargs[k]))
  95. return add_params_to_qs(body, params)
  96. def prepare_token_revocation_request(url, token, token_type_hint="access_token",
  97. callback=None, body='', **kwargs):
  98. """Prepare a token revocation request.
  99. The client constructs the request by including the following parameters
  100. using the "application/x-www-form-urlencoded" format in the HTTP request
  101. entity-body:
  102. token REQUIRED. The token that the client wants to get revoked.
  103. token_type_hint OPTIONAL. A hint about the type of the token submitted
  104. for revocation. Clients MAY pass this parameter in order to help the
  105. authorization server to optimize the token lookup. If the server is unable
  106. to locate the token using the given hint, it MUST extend its search across
  107. all of its supported token types. An authorization server MAY ignore this
  108. parameter, particularly if it is able to detect the token type
  109. automatically. This specification defines two such values:
  110. * access_token: An access token as defined in [RFC6749],
  111. `Section 1.4`_
  112. * refresh_token: A refresh token as defined in [RFC6749],
  113. `Section 1.5`_
  114. Specific implementations, profiles, and extensions of this
  115. specification MAY define other values for this parameter using the
  116. registry defined in `Section 4.1.2`_.
  117. .. _`Section 1.4`: http://tools.ietf.org/html/rfc6749#section-1.4
  118. .. _`Section 1.5`: http://tools.ietf.org/html/rfc6749#section-1.5
  119. .. _`Section 4.1.2`: http://tools.ietf.org/html/rfc7009#section-4.1.2
  120. """
  121. if not is_secure_transport(url):
  122. raise InsecureTransportError()
  123. params = [('token', token)]
  124. if token_type_hint:
  125. params.append(('token_type_hint', token_type_hint))
  126. for k in kwargs:
  127. if kwargs[k]:
  128. params.append((unicode_type(k), kwargs[k]))
  129. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  130. if callback:
  131. params.append(('callback', callback))
  132. return add_params_to_uri(url, params), headers, body
  133. else:
  134. return url, headers, add_params_to_qs(body, params)
  135. def parse_authorization_code_response(uri, state=None):
  136. """Parse authorization grant response URI into a dict.
  137. If the resource owner grants the access request, the authorization
  138. server issues an authorization code and delivers it to the client by
  139. adding the following parameters to the query component of the
  140. redirection URI using the ``application/x-www-form-urlencoded`` format:
  141. **code**
  142. REQUIRED. The authorization code generated by the
  143. authorization server. The authorization code MUST expire
  144. shortly after it is issued to mitigate the risk of leaks. A
  145. maximum authorization code lifetime of 10 minutes is
  146. RECOMMENDED. The client MUST NOT use the authorization code
  147. more than once. If an authorization code is used more than
  148. once, the authorization server MUST deny the request and SHOULD
  149. revoke (when possible) all tokens previously issued based on
  150. that authorization code. The authorization code is bound to
  151. the client identifier and redirection URI.
  152. **state**
  153. REQUIRED if the "state" parameter was present in the client
  154. authorization request. The exact value received from the
  155. client.
  156. :param uri: The full redirect URL back to the client.
  157. :param state: The state parameter from the authorization request.
  158. For example, the authorization server redirects the user-agent by
  159. sending the following HTTP response:
  160. .. code-block:: http
  161. HTTP/1.1 302 Found
  162. Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
  163. &state=xyz
  164. """
  165. if not is_secure_transport(uri):
  166. raise InsecureTransportError()
  167. query = urlparse.urlparse(uri).query
  168. params = dict(urlparse.parse_qsl(query))
  169. if not 'code' in params:
  170. raise MissingCodeError("Missing code parameter in response.")
  171. if state and params.get('state', None) != state:
  172. raise MismatchingStateError()
  173. return params
  174. def parse_implicit_response(uri, state=None, scope=None):
  175. """Parse the implicit token response URI into a dict.
  176. If the resource owner grants the access request, the authorization
  177. server issues an access token and delivers it to the client by adding
  178. the following parameters to the fragment component of the redirection
  179. URI using the ``application/x-www-form-urlencoded`` format:
  180. **access_token**
  181. REQUIRED. The access token issued by the authorization server.
  182. **token_type**
  183. REQUIRED. The type of the token issued as described in
  184. Section 7.1. Value is case insensitive.
  185. **expires_in**
  186. RECOMMENDED. The lifetime in seconds of the access token. For
  187. example, the value "3600" denotes that the access token will
  188. expire in one hour from the time the response was generated.
  189. If omitted, the authorization server SHOULD provide the
  190. expiration time via other means or document the default value.
  191. **scope**
  192. OPTIONAL, if identical to the scope requested by the client,
  193. otherwise REQUIRED. The scope of the access token as described
  194. by Section 3.3.
  195. **state**
  196. REQUIRED if the "state" parameter was present in the client
  197. authorization request. The exact value received from the
  198. client.
  199. Similar to the authorization code response, but with a full token provided
  200. in the URL fragment:
  201. .. code-block:: http
  202. HTTP/1.1 302 Found
  203. Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
  204. &state=xyz&token_type=example&expires_in=3600
  205. """
  206. if not is_secure_transport(uri):
  207. raise InsecureTransportError()
  208. fragment = urlparse.urlparse(uri).fragment
  209. params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True))
  210. if 'scope' in params:
  211. params['scope'] = scope_to_list(params['scope'])
  212. if 'expires_in' in params:
  213. params['expires_at'] = time.time() + int(params['expires_in'])
  214. if state and params.get('state', None) != state:
  215. raise ValueError("Mismatching or missing state in params.")
  216. params = OAuth2Token(params, old_scope=scope)
  217. validate_token_parameters(params)
  218. return params
  219. def parse_token_response(body, scope=None):
  220. """Parse the JSON token response body into a dict.
  221. The authorization server issues an access token and optional refresh
  222. token, and constructs the response by adding the following parameters
  223. to the entity body of the HTTP response with a 200 (OK) status code:
  224. access_token
  225. REQUIRED. The access token issued by the authorization server.
  226. token_type
  227. REQUIRED. The type of the token issued as described in
  228. `Section 7.1`_. Value is case insensitive.
  229. expires_in
  230. RECOMMENDED. The lifetime in seconds of the access token. For
  231. example, the value "3600" denotes that the access token will
  232. expire in one hour from the time the response was generated.
  233. If omitted, the authorization server SHOULD provide the
  234. expiration time via other means or document the default value.
  235. refresh_token
  236. OPTIONAL. The refresh token which can be used to obtain new
  237. access tokens using the same authorization grant as described
  238. in `Section 6`_.
  239. scope
  240. OPTIONAL, if identical to the scope requested by the client,
  241. otherwise REQUIRED. The scope of the access token as described
  242. by `Section 3.3`_.
  243. The parameters are included in the entity body of the HTTP response
  244. using the "application/json" media type as defined by [`RFC4627`_]. The
  245. parameters are serialized into a JSON structure by adding each
  246. parameter at the highest structure level. Parameter names and string
  247. values are included as JSON strings. Numerical values are included
  248. as JSON numbers. The order of parameters does not matter and can
  249. vary.
  250. :param body: The full json encoded response body.
  251. :param scope: The scope requested during authorization.
  252. For example:
  253. .. code-block:: http
  254. HTTP/1.1 200 OK
  255. Content-Type: application/json
  256. Cache-Control: no-store
  257. Pragma: no-cache
  258. {
  259. "access_token":"2YotnFZFEjr1zCsicMWpAA",
  260. "token_type":"example",
  261. "expires_in":3600,
  262. "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
  263. "example_parameter":"example_value"
  264. }
  265. .. _`Section 7.1`: http://tools.ietf.org/html/rfc6749#section-7.1
  266. .. _`Section 6`: http://tools.ietf.org/html/rfc6749#section-6
  267. .. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3
  268. .. _`RFC4627`: http://tools.ietf.org/html/rfc4627
  269. """
  270. try:
  271. params = json.loads(body)
  272. except ValueError:
  273. # Fall back to URL-encoded string, to support old implementations,
  274. # including (at time of writing) Facebook. See:
  275. # https://github.com/idan/oauthlib/issues/267
  276. params = dict(urlparse.parse_qsl(body))
  277. for key in ('expires_in', 'expires'):
  278. if key in params: # cast a couple things to int
  279. params[key] = int(params[key])
  280. if 'scope' in params:
  281. params['scope'] = scope_to_list(params['scope'])
  282. if 'expires' in params:
  283. params['expires_in'] = params.pop('expires')
  284. if 'expires_in' in params:
  285. params['expires_at'] = time.time() + int(params['expires_in'])
  286. params = OAuth2Token(params, old_scope=scope)
  287. validate_token_parameters(params)
  288. return params
  289. def validate_token_parameters(params):
  290. """Ensures token precence, token type, expiration and scope in params."""
  291. if 'error' in params:
  292. raise_from_error(params.get('error'), params)
  293. if not 'access_token' in params:
  294. raise MissingTokenError(description="Missing access token parameter.")
  295. if not 'token_type' in params:
  296. if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
  297. raise MissingTokenTypeError()
  298. # If the issued access token scope is different from the one requested by
  299. # the client, the authorization server MUST include the "scope" response
  300. # parameter to inform the client of the actual scope granted.
  301. # http://tools.ietf.org/html/rfc6749#section-3.3
  302. if params.scope_changed:
  303. message = 'Scope has changed from "{old}" to "{new}".'.format(
  304. old=params.old_scope, new=params.scope,
  305. )
  306. scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
  307. if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
  308. w = Warning(message)
  309. w.token = params
  310. w.old_scope = params.old_scopes
  311. w.new_scope = params.scopes
  312. raise w