mobile_application.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth2.rfc6749
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. This module is an implementation of various logic needed
  6. for consuming and providing OAuth 2.0 RFC6749.
  7. """
  8. from ..parameters import parse_implicit_response, prepare_grant_uri
  9. from .base import Client
  10. class MobileApplicationClient(Client):
  11. """A public client utilizing the implicit code grant workflow.
  12. A user-agent-based application is a public client in which the
  13. client code is downloaded from a web server and executes within a
  14. user-agent (e.g. web browser) on the device used by the resource
  15. owner. Protocol data and credentials are easily accessible (and
  16. often visible) to the resource owner. Since such applications
  17. reside within the user-agent, they can make seamless use of the
  18. user-agent capabilities when requesting authorization.
  19. The implicit grant type is used to obtain access tokens (it does not
  20. support the issuance of refresh tokens) and is optimized for public
  21. clients known to operate a particular redirection URI. These clients
  22. are typically implemented in a browser using a scripting language
  23. such as JavaScript.
  24. As a redirection-based flow, the client must be capable of
  25. interacting with the resource owner's user-agent (typically a web
  26. browser) and capable of receiving incoming requests (via redirection)
  27. from the authorization server.
  28. Unlike the authorization code grant type in which the client makes
  29. separate requests for authorization and access token, the client
  30. receives the access token as the result of the authorization request.
  31. The implicit grant type does not include client authentication, and
  32. relies on the presence of the resource owner and the registration of
  33. the redirection URI. Because the access token is encoded into the
  34. redirection URI, it may be exposed to the resource owner and other
  35. applications residing on the same device.
  36. """
  37. response_type = 'token'
  38. def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
  39. state=None, **kwargs):
  40. """Prepare the implicit grant request URI.
  41. The client constructs the request URI by adding the following
  42. parameters to the query component of the authorization endpoint URI
  43. using the "application/x-www-form-urlencoded" format, per `Appendix B`_:
  44. :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI
  45. and it should have been registered with the OAuth
  46. provider prior to use. As described in `Section 3.1.2`_.
  47. :param scope: OPTIONAL. The scope of the access request as described by
  48. Section 3.3`_. These may be any string but are commonly
  49. URIs or various categories such as ``videos`` or ``documents``.
  50. :param state: RECOMMENDED. An opaque value used by the client to maintain
  51. state between the request and callback. The authorization
  52. server includes this value when redirecting the user-agent back
  53. to the client. The parameter SHOULD be used for preventing
  54. cross-site request forgery as described in `Section 10.12`_.
  55. :param kwargs: Extra arguments to include in the request URI.
  56. In addition to supplied parameters, OAuthLib will append the ``client_id``
  57. that was provided in the constructor as well as the mandatory ``response_type``
  58. argument, set to ``token``::
  59. >>> from oauthlib.oauth2 import MobileApplicationClient
  60. >>> client = MobileApplicationClient('your_id')
  61. >>> client.prepare_request_uri('https://example.com')
  62. 'https://example.com?client_id=your_id&response_type=token'
  63. >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')
  64. 'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'
  65. >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])
  66. 'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'
  67. >>> client.prepare_request_uri('https://example.com', foo='bar')
  68. 'https://example.com?client_id=your_id&response_type=token&foo=bar'
  69. .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
  70. .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
  71. .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
  72. .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
  73. .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
  74. """
  75. scope = self.scope if scope is None else scope
  76. return prepare_grant_uri(uri, self.client_id, self.response_type,
  77. redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)
  78. def parse_request_uri_response(self, uri, state=None, scope=None):
  79. """Parse the response URI fragment.
  80. If the resource owner grants the access request, the authorization
  81. server issues an access token and delivers it to the client by adding
  82. the following parameters to the fragment component of the redirection
  83. URI using the "application/x-www-form-urlencoded" format:
  84. :param uri: The callback URI that resulted from the user being redirected
  85. back from the provider to you, the client.
  86. :param state: The state provided in the authorization request.
  87. :param scope: The scopes provided in the authorization request.
  88. :return: Dictionary of token parameters.
  89. :raises: OAuth2Error if response is invalid.
  90. A successful response should always contain
  91. **access_token**
  92. The access token issued by the authorization server. Often
  93. a random string.
  94. **token_type**
  95. The type of the token issued as described in `Section 7.1`_.
  96. Commonly ``Bearer``.
  97. **state**
  98. If you provided the state parameter in the authorization phase, then
  99. the provider is required to include that exact state value in the
  100. response.
  101. While it is not mandated it is recommended that the provider include
  102. **expires_in**
  103. The lifetime in seconds of the access token. For
  104. example, the value "3600" denotes that the access token will
  105. expire in one hour from the time the response was generated.
  106. If omitted, the authorization server SHOULD provide the
  107. expiration time via other means or document the default value.
  108. **scope**
  109. Providers may supply this in all responses but are required to only
  110. if it has changed since the authorization request.
  111. A few example responses can be seen below::
  112. >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world'
  113. >>> from oauthlib.oauth2 import MobileApplicationClient
  114. >>> client = MobileApplicationClient('your_id')
  115. >>> client.parse_request_uri_response(response_uri)
  116. {
  117. 'access_token': 'sdlfkj452',
  118. 'token_type': 'Bearer',
  119. 'state': 'ss345asyht',
  120. 'scope': [u'hello', u'world']
  121. }
  122. >>> client.parse_request_uri_response(response_uri, state='other')
  123. Traceback (most recent call last):
  124. File "<stdin>", line 1, in <module>
  125. File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response
  126. **scope**
  127. File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response
  128. raise ValueError("Mismatching or missing state in params.")
  129. ValueError: Mismatching or missing state in params.
  130. >>> def alert_scope_changed(message, old, new):
  131. ... print(message, old, new)
  132. ...
  133. >>> oauthlib.signals.scope_changed.connect(alert_scope_changed)
  134. >>> client.parse_request_body_response(response_body, scope=['other'])
  135. ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world'])
  136. .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
  137. .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
  138. """
  139. scope = self.scope if scope is None else scope
  140. self.token = parse_implicit_response(uri, state=state, scope=scope)
  141. self.populate_token_attributes(self.token)
  142. return self.token