client.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. """
  2. The MIT License
  3. Copyright (c) 2007 Leah Culver
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. Example consumer. This is not recommended for production.
  20. Instead, you'll want to create your own subclass of OAuthClient
  21. or find one that works with your web framework.
  22. """
  23. import httplib
  24. import time
  25. import oauth.oauth as oauth
  26. # settings for the local test consumer
  27. SERVER = 'localhost'
  28. PORT = 8080
  29. # fake urls for the test server (matches ones in server.py)
  30. REQUEST_TOKEN_URL = 'https://photos.example.net/request_token'
  31. ACCESS_TOKEN_URL = 'https://photos.example.net/access_token'
  32. AUTHORIZATION_URL = 'https://photos.example.net/authorize'
  33. CALLBACK_URL = 'http://printer.example.com/request_token_ready'
  34. RESOURCE_URL = 'http://photos.example.net/photos'
  35. # key and secret granted by the service provider for this consumer application - same as the MockOAuthDataStore
  36. CONSUMER_KEY = 'key'
  37. CONSUMER_SECRET = 'secret'
  38. # example client using httplib with headers
  39. class SimpleOAuthClient(oauth.OAuthClient):
  40. def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='', access_token_url='', authorization_url=''):
  41. self.server = server
  42. self.port = port
  43. self.request_token_url = request_token_url
  44. self.access_token_url = access_token_url
  45. self.authorization_url = authorization_url
  46. self.connection = httplib.HTTPConnection("%s:%d" % (self.server, self.port))
  47. def fetch_request_token(self, oauth_request):
  48. # via headers
  49. # -> OAuthToken
  50. self.connection.request(oauth_request.http_method, self.request_token_url, headers=oauth_request.to_header())
  51. response = self.connection.getresponse()
  52. return oauth.OAuthToken.from_string(response.read())
  53. def fetch_access_token(self, oauth_request):
  54. # via headers
  55. # -> OAuthToken
  56. self.connection.request(oauth_request.http_method, self.access_token_url, headers=oauth_request.to_header())
  57. response = self.connection.getresponse()
  58. return oauth.OAuthToken.from_string(response.read())
  59. def authorize_token(self, oauth_request):
  60. # via url
  61. # -> typically just some okay response
  62. self.connection.request(oauth_request.http_method, oauth_request.to_url())
  63. response = self.connection.getresponse()
  64. return response.read()
  65. def access_resource(self, oauth_request):
  66. # via post body
  67. # -> some protected resources
  68. headers = {'Content-Type' :'application/x-www-form-urlencoded'}
  69. self.connection.request('POST', RESOURCE_URL, body=oauth_request.to_postdata(), headers=headers)
  70. response = self.connection.getresponse()
  71. return response.read()
  72. def run_example():
  73. # setup
  74. print '** OAuth Python Library Example **'
  75. client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL)
  76. consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
  77. signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
  78. signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
  79. pause()
  80. # get request token
  81. print '* Obtain a request token ...'
  82. pause()
  83. oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
  84. oauth_request.sign_request(signature_method_plaintext, consumer, None)
  85. print 'REQUEST (via headers)'
  86. print 'parameters: %s' % str(oauth_request.parameters)
  87. pause()
  88. token = client.fetch_request_token(oauth_request)
  89. print 'GOT'
  90. print 'key: %s' % str(token.key)
  91. print 'secret: %s' % str(token.secret)
  92. print 'callback confirmed? %s' % str(token.callback_confirmed)
  93. pause()
  94. print '* Authorize the request token ...'
  95. pause()
  96. oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, http_url=client.authorization_url)
  97. print 'REQUEST (via url query string)'
  98. print 'parameters: %s' % str(oauth_request.parameters)
  99. pause()
  100. # this will actually occur only on some callback
  101. response = client.authorize_token(oauth_request)
  102. print 'GOT'
  103. print response
  104. # sad way to get the verifier
  105. import urlparse, cgi
  106. query = urlparse.urlparse(response)[4]
  107. params = cgi.parse_qs(query, keep_blank_values=False)
  108. verifier = params['oauth_verifier'][0]
  109. print 'verifier: %s' % verifier
  110. pause()
  111. # get access token
  112. print '* Obtain an access token ...'
  113. pause()
  114. oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier, http_url=client.access_token_url)
  115. oauth_request.sign_request(signature_method_plaintext, consumer, token)
  116. print 'REQUEST (via headers)'
  117. print 'parameters: %s' % str(oauth_request.parameters)
  118. pause()
  119. token = client.fetch_access_token(oauth_request)
  120. print 'GOT'
  121. print 'key: %s' % str(token.key)
  122. print 'secret: %s' % str(token.secret)
  123. pause()
  124. # access some protected resources
  125. print '* Access protected resources ...'
  126. pause()
  127. parameters = {'file': 'vacation.jpg', 'size': 'original'} # resource specific params
  128. oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='POST', http_url=RESOURCE_URL, parameters=parameters)
  129. oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
  130. print 'REQUEST (via post body)'
  131. print 'parameters: %s' % str(oauth_request.parameters)
  132. pause()
  133. params = client.access_resource(oauth_request)
  134. print 'GOT'
  135. print 'non-oauth parameters: %s' % params
  136. pause()
  137. def pause():
  138. print ''
  139. time.sleep(1)
  140. if __name__ == '__main__':
  141. run_example()
  142. print 'Done.'