def __init__(self, *args, **kwargs): self.oauth_server = oauth.Server(MockOAuthDataStore()) self.oauth_server.add_signature_method( oauth.SignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.SignatureMethod_HMAC_SHA1()) BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def verify_oauth_request(request, oauth_request, consumer, token=None): """ Helper function to verify requests. """ from .store import get_store_singleton # Check nonce if not get_store_singleton().check_nonce(request, oauth_request, oauth_request['oauth_nonce'], oauth_request['oauth_timestamp']): return False # Verify request try: oauth_server = oauth.Server() oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT()) # Ensure the passed keys and secrets are ascii, or HMAC will complain. consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'), consumer.secret.encode('ascii', 'ignore')) if token is not None: token = oauth.Token(token.key.encode('ascii', 'ignore'), token.secret.encode('ascii', 'ignore')) oauth_server.verify_request(oauth_request, consumer, token) except oauth.Error as err: return False return True
def _make_querystring_with_HMAC_SHA1(self, http_method, path, data, content_type): """ Utility method for creating a request which is signed using HMAC_SHA1 method """ consumer = oauth.Consumer(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET) token = oauth.Token(key=self.access_token.key, secret=self.access_token.secret) url = "http://testserver:80" + path #if data is json, we want it in the body, else as parameters (i.e. queryparams on get) parameters = None body = "" if content_type == "application/json": body = data else: parameters = data request = oauth.Request.from_consumer_and_token( consumer=consumer, token=token, http_method=http_method, http_url=url, parameters=parameters, body=body) # Sign the request. signature_method = oauth.SignatureMethod_HMAC_SHA1() request.sign_request(signature_method, consumer, token) return request.to_url()
def _make_auth_header_with_HMAC_SHA1(self, http_method, path, get_params, body_params, is_form_encoded): """make auth header, take in consideration both get and post body_params """ consumer = oauth.Consumer(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET) token = oauth.Token(key=self.ACCESS_TOKEN_KEY, secret=self.ACCESS_TOKEN_SECRET) url = "http://testserver:80" + path body = urlencode(body_params) params = {} params.update(get_params) params.update(body_params) request = oauth.Request.from_consumer_and_token( consumer=consumer, token=token, http_method=http_method, http_url=url, is_form_encoded=is_form_encoded, body=body, # it seems that body parameter isn't enough to have body params # in signature base string parameters=params ) # Sign the request. signature_method = oauth.SignatureMethod_HMAC_SHA1() request.sign_request(signature_method, consumer, token) return request.to_header()
def initialize_server_request(request): """Shortcut for initialization.""" oauth_request = get_oauth_request(request) if oauth_request: oauth_server = oauth.Server() if 'plaintext' in OAUTH_SIGNATURE_METHODS: oauth_server.add_signature_method( oauth.SignatureMethod_PLAINTEXT()) if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS: oauth_server.add_signature_method( oauth.SignatureMethod_HMAC_SHA1()) else: oauth_server = None return oauth_server, oauth_request
def _make_GET_auth_header(self, url): token = oauth.Token(self.ACCESS_TOKEN_KEY, self.ACCESS_TOKEN_SECRET) consumer = oauth.Consumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) request = oauth.Request.from_consumer_and_token( consumer=consumer, token=token, http_method="GET", http_url=url, ) # Sign the request. signature_method = oauth.SignatureMethod_HMAC_SHA1() request.sign_request(signature_method, consumer, token) return request.to_header()["Authorization"]
def test_positive(self): # Then consumer obtains a Request Token parameters = self._make_request_token_parameters() response = self.c.get("/oauth/request_token/", parameters) # The Service Provider checks the signature and replies with an unauthorized Request Token in the body of the HTTP response self._validate_request_token_response(response) token = self._last_created_request_token() parameters = {'oauth_token': token.key} # The Consumer redirects Jane's browser to the Service Provider User # Authorization URL to obtain Jane's approval for accessing her private # photos. response = self.c.get("/oauth/authorize/", parameters) # The Service Provider asks Jane to sign-in using her username and password self.assertEqual(response.status_code, 302) expected_redirect = '/accounts/login/?next=/oauth/authorize/%3Foauth_token%3D{0}'.format( token.key) self.assertIn(expected_redirect, response['Location']) # Jane logins self.c.login(username='******', password='******') # If successful, Service Provider asks her if she approves granting # printer.example.com access to her private photos. response = self.c.get("/oauth/authorize/", parameters) self.assertEqual(response.status_code, 200) self.assertTrue( response.content.startswith( b'Fake authorize view for printer.example.com with params: oauth_token=' )) # Jane approves the request. self.assertEqual(token.is_approved, 0) # token is not approved yet parameters['authorize_access'] = 1 response = self.c.post("/oauth/authorize/", parameters) # The Service Provider redirects her back to the Consumer's callback URL self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].startswith( 'http://printer.example.com/request_token_ready?oauth_verifier=')) self.assertTrue('oauth_token=' in response['Location']) token = self._last_created_request_token( ) # get from the DB updated token self.assertTrue(token.is_approved) ## Obtaining an Access Token # Now that the Consumer knows Jane approved the Request Token, #it asks the Service Provider to exchange it for an Access Token # reset Client self.c = Client() parameters = self._make_access_token_parameters(token) response = self.c.get("/oauth/access_token/", parameters) # The Service Provider checks the signature and replies with an # Access Token in the body of the HTTP response self.assertEqual(response.status_code, 200) response_params = cgi.parse_qs(response.content) access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] self.assertEqual(response_params[b'oauth_token'][0], access_token.key.encode('utf-8')) self.assertEqual(response_params[b'oauth_token_secret'][0], access_token.secret.encode('utf-8')) self.assertEqual(access_token.user.username, 'jane') ## Accessing protected resources # # The Consumer is now ready to request the private photo. # Since the photo URL is not secure (HTTP), it must use HMAC-SHA1. ## Generating Signature Base String # To generate the signature, it first needs to generate the Signature # Base String. The request contains the following parameters (oauth_ # signature excluded) which are ordered and concatenated into a # normalized string parameters = self._make_protected_access_parameters(access_token) ## Calculating Signature Value # HMAC-SHA1 produces the following digest value as a base64-encoded # string (using the Signature Base String as text and # self.CONSUMER_SECRET as key) oauth_request = oauth.Request.from_token_and_callback( access_token, http_url='http://testserver/oauth/photo/', parameters=parameters) signature_method = oauth.SignatureMethod_HMAC_SHA1() signature = signature_method.sign(oauth_request, self.consumer, access_token) # Requesting Protected Resource # All together, the Consumer request for the photo is: parameters['oauth_signature'] = signature response = self.c.get("/oauth/photo/", parameters) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'Protected Resource access!') # Revoking Access # If Jane deletes the Access Token of printer.example.com, # the Consumer will not be able to access the Protected Resource anymore access_token.delete() # Note that an "Invalid signature" error will be raised here if the # token is not revoked by Jane because we reuse a previously used one. parameters['oauth_signature'] = signature parameters['oauth_nonce'] = 'yetanotheraccessscopenonce' response = self.c.get(self.scope.url, parameters) self.assertEqual(response.status_code, 401) self.assertTrue(response.content.startswith(b'Invalid access token:'))
def run_example(): # setup print('** OAuth Python Library Example **') client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL) consumer = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET) signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT() signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() pause() # get request token print('* Obtain a request token ...') pause() oauth_request = oauth.Request.from_consumer_and_token( consumer, http_url=client.request_token_url) oauth_request.sign_request(signature_method_plaintext, consumer, None) print('REQUEST (via headers)') print('parameters: %s' % str(dict(oauth_request))) pause() token = client.fetch_request_token(oauth_request) print('GOT') print('key: %s' % str(token.key)) print('secret: %s' % str(token.secret)) print('callback confirmed? %s' % str(token.callback_confirmed)) pause() print('* Authorize the request token ...') pause() oauth_request = oauth.Request.from_token_and_callback( token=token, http_url=client.authorization_url) print('REQUEST (via url query string)') print('parameters: %s' % str(oauth_request.parameters)) pause() # this will actually occur only on some callback response = client.authorize_token(oauth_request) print('GOT') print(response) # sad way to get the verifier import urlparse import cgi query = urlparse.urlparse(response)[4] params = cgi.parse_qs(query, keep_blank_values=False) verifier = params['oauth_verifier'][0] print('verifier: %s' % verifier) pause() # get access token print('* Obtain an access token ...') pause() oauth_request = oauth.Request.from_consumer_and_token( consumer, token=token, verifier=verifier, http_url=client.access_token_url) oauth_request.sign_request(signature_method_plaintext, consumer, token) print('REQUEST (via headers)') print('parameters: %s' % str(oauth_request.parameters)) pause() token = client.fetch_access_token(oauth_request) print('GOT') print('key: %s' % str(token.key)) print('secret: %s' % str(token.secret)) pause() # access some protected resources print('* Access protected resources ...') pause() parameters = {'file': 'vacation.jpg', 'size': 'original'} # resource specific params oauth_request = oauth.Request.from_consumer_and_token( consumer, token=token, http_method='POST', http_url=RESOURCE_URL, parameters=parameters ) oauth_request.sign_request(signature_method_hmac_sha1, consumer, token) print('REQUEST (via post body)') print('parameters: %s' % str(oauth_request.parameters)) pause() params = client.access_resource(oauth_request) print('GOT') print('non-oauth parameters: %s' % params) pause()
def __init__(self): self._server = oauth.Server() self._server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) self._server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())