def get_signature_base_string(self, method, url, params): """ Builds the signature base string (as defined by OAuth) for this request. Args: method: string The HTTP method used for signing the request. url: string The fully-qualified url of the request. params: string Parameters used to sign the request. Should be a merged set of all querystring, form-urlencoded POST body, and header params. Returns: string A signature base string as defined by the OAuth spec. """ encoded_params = {} for key, value in params.items(): encoded_params[key] = value.encode('utf-8', 'ignore') oauth_request = oauth.OAuthRequest(http_method=method.upper(), http_url=url, parameters=encoded_params) base_str = '&'.join( (oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()))) return base_str
def test_validate_signature(self): auth_header = 'OAuth oauth_nonce="8982120766",oauth_timestamp="1234814886",oauth_consumer_key="myck",oauth_signature_method="PLAINTEXT",oauth_version="1.0",oauth_signature="%26"' request = oauth.OAuthRequest('http://daaku.org/', headers={'Authorization': auth_header}, timestamp_threshold=1234567890) request.validate_signature(OAuthSignatureMethod_PLAINTEXT, {'oauth_token': 'myck'})
def authorize_request(self, url, method, headers, parameters): request = oauth.OAuthRequest(http_method=method, http_url=url, parameters=parameters) request.sign_request(self._sigmethod, self._consumer, self.access_token) return request.to_url()
def test_missing_timestamp(self): request = oauth.OAuthRequest('http://daaku.org/') try: request.validate_signature(OAuthSignatureMethod_PLAINTEXT, {'oauth_token': 'myck'}) except oauth.OAuthError, e: self.assert_(True)
def test_realm_in_auth_header(self): request = oauth.OAuthRequest( url='http://daaku.org/', headers={ 'Authorization': 'OAuth realm="daaku.org",oauth_version="1.0"' }) self.assertEqual(request.params, {'oauth_version': '1.0'})
def set_verifier(self, oauth_verifier): if self.request_token is None: raise AuthHandlerError( "Request token is not defined. This ususally means that the access token has been loaded from a file." ) self.request_token.set_verifier(oauth_verifier) access_token_parms = { 'oauth_consumer_key': self.key, 'oauth_nonce': oauth.generate_nonce(), 'oauth_signature_method': "HMAC-SHA1", 'oauth_timestamp': str(int(time.time())), 'oauth_token': self.request_token.key, 'oauth_verifier': self.request_token.verifier } req = oauth.OAuthRequest(http_method="GET", http_url=ACCESS_TOKEN_URL, parameters=access_token_parms) req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, self.request_token) resp = urllib2.urlopen(req.to_url()) access_token_resp = dict(urlparse.parse_qsl(resp.read())) self.access_token = oauth.OAuthToken( access_token_resp["oauth_token"], access_token_resp["oauth_token_secret"])
def _signature_request(consumer_token, method, url, args, _access_token): """ return signature_request by params """ params = {} params.update(args) req = oauth.OAuthRequest(method, url, params) sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1() return sigmethod.build_signature(req, consumer_token, _access_token)
def test_incomplete_base_sig_method(self): request = oauth.OAuthRequest('http://daaku.org/') try: request.sign_request(OAuthSignatureMethod, {'oauth_token': 'myck'}) except NotImplementedError: self.assert_(True) else: self.assert_(False, 'Expected NotImplementedError')
def test_auth_header(self): request = oauth.OAuthRequest( url='http://daaku.org/', http_method='POST', headers={'Authorization': 'OAuth oauth_version="1.0"'}) self.assertEqual(request.url, 'http://daaku.org/') self.assertEqual(request.http_method, 'POST') self.assertEqual(request.params, {'oauth_version': '1.0'})
def test_invalid_auth_header_no_data(self): try: request = oauth.OAuthRequest(url='http://daaku.org/', headers={'Authorization': 'OAuth '}) except oauth.OAuthError: self.assert_(True) else: self.assert_(False, 'Was expecting OAuthError to be raised')
def get_signed_url(self, url, method, headers, parameters): """only sign url, no authentication""" # OAuthRequest(http_method, http_url, parameters) request = oauth.OAuthRequest(http_method=method, http_url=url, parameters=parameters) request.sign_request(self._sigmethod, self._consumer, self.access_token) return request.to_url()
def make_request(self, parameter=None): req = oauth.OAuthRequest(http_method="GET", http_url=self.url, parameters=parameter) req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, self.token) url = req.to_url() return url
def test_validate_signature(self): auth_header = 'OAuth oauth_nonce="3952607326",oauth_timestamp="1234814428",oauth_consumer_key="myck",oauth_signature_method="HMAC-SHA1",oauth_version="1.0",oauth_signature="ct4wwv2DUVu463wZEjXIgHu5pK8%3D"' request = oauth.OAuthRequest('http://daaku.org/', headers={'Authorization': auth_header}, timestamp_threshold=1234567890) consumer = { 'oauth_token': 'myck', 'oauth_token_secret': 'mycks', } request.validate_signature(OAuthSignatureMethod_HMAC_SHA1, consumer)
def test_normalized_request_params(self): request = oauth.OAuthRequest( url='http://daaku.org/?a=1', http_method='POST', params={'b': '2'}, headers={ 'Authorization': 'OAuth realm="daaku.org",oauth_version="1.0"' }) self.assertEqual(request.normalized_request_params, 'a=1&b=2&oauth_version=1.0')
def test_expired_timestamp(self): auth_header = 'OAuth oauth_nonce="8982120766",oauth_timestamp="1234814886",oauth_consumer_key="myck",oauth_signature_method="PLAINTEXT",oauth_version="1.0",oauth_signature="%26"' request = oauth.OAuthRequest( 'http://daaku.org/', headers={'Authorization': auth_header}, ) try: request.validate_signature(OAuthSignatureMethod_PLAINTEXT, {'oauth_token': 'myck'}) except oauth.OAuthError, e: self.assert_(True)
def test_invalid_sign_method(self): request = oauth.OAuthRequest('http://daaku.org/', params={ 'oauth_timestamp': 1234814886, 'oauth_signature_method': 'blah' }, timestamp_threshold=1234567890) try: request.validate_signature(OAuthSignatureMethod_PLAINTEXT, {'oauth_token': 'myck'}) except oauth.OAuthError, e: self.assert_(True)
def __init__(self, key=None, secret=None, callback=None, access_token_key=None, access_token_secret=None, request_token_key=None, request_token_secret=None): self.key = key or method_call.API_KEY self.secret = secret or method_call.API_SECRET if self.key is None or self.secret is None: raise ValueError("API keys have not been set.") if callback is None: callback = "http://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=%s" % self.key params = { 'oauth_timestamp': str(int(time.time())), 'oauth_signature_method': "HMAC-SHA1", 'oauth_version': "1.0", 'oauth_callback': callback, 'oauth_nonce': oauth.generate_nonce(), 'oauth_consumer_key': self.key } self.consumer = oauth.OAuthConsumer(key=self.key, secret=self.secret) if (access_token_key is None) and (request_token_key is None): req = oauth.OAuthRequest(http_method="GET", http_url=TOKEN_REQUEST_URL, parameters=params) req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, None) resp = urllib2.urlopen(req.to_url()) request_token = dict(urlparse.parse_qsl(resp.read())) self.request_token = oauth.OAuthToken( request_token['oauth_token'], request_token['oauth_token_secret']) self.access_token = None elif request_token_key is not None: self.access_token = None self.request_token = oauth.OAuthToken(request_token_key, request_token_secret) else: self.request_token = None self.access_token = oauth.OAuthToken(access_token_key, access_token_secret)
def make_oauth_request(self, http_method='GET', http_url={}, has_param=False, parameters=None, token=None): param = { 'oauth_version': '1.0', 'oauth_timestamp': int(time.time()), 'oauth_nonce': oauth.generate_nonce(), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_consumer_key': self.consumer.key } if (parameters): param.update(parameters) if (token): param.update({'oauth_token': token.key}) oauth_request = oauth.OAuthRequest(http_method=http_method, http_url=http_url, parameters=param) oauth_request.sign_request(self.signature_method, self.consumer, token) oauth_header = oauth_request.to_header() if http_method == 'POST': postdata = oauth_request.to_postdata() req = urllib2.Request(http_url, postdata, oauth_header) else: if has_param: url = oauth_request.to_url() req = urllib2.Request(url) else: url = http_url req = urllib2.Request(url, None, oauth_header) try: req = urllib2.urlopen(req) return req.read() except urllib2.URLError as e: return e except urllib2.HTTPError as e: return e
def is_valid_signature(self, request): """ Validates the incoming **2 legged** signed request. This is useful for signed requests from OpenSocial Containers such as YAP. It calls OAuthRequest.validate_signature which throws an OAuthError if the signature validation fails. **FIXME** Missing nonce validation. """ oauth_request = oauth.OAuthRequest( request.build_absolute_uri(request.path), request.method, dict(request.REQUEST.items()), {'Authorization': request.META.get('HTTP_AUTHORIZATION', '')}, ) oauth_request.validate_signature(self.sig_method, self.consumer)
def _isValidSignature(self): # Code lab hack: # If the container is 'appengine' (e.g. app is running on localhost), return True if self.request.get('oauth_consumer_key') == 'appengine': return True # Construct a RSA.pubkey object exponent = 65537 public_key_str = """0x\ 00b1e057678343866db89d7dec2518\ 99261bf2f5e0d95f5d868f81d600c9\ a101c9e6da20606290228308551ed3\ acf9921421dcd01ef1de35dd3275cd\ 4983c7be0be325ce8dfc3af6860f7a\ b0bf32742cd9fb2fcd1cd1756bbc40\ 0b743f73acefb45d26694caf4f26b9\ 765b9f65665245524de957e8c547c3\ 58781fdfb68ec056d1""" public_key_long = long(public_key_str, 16) public_key = RSA.construct((public_key_long, exponent)) # Rebuild the message hash locally oauth_request = oauth.OAuthRequest(http_method=self.request.method, http_url=self.request.url, parameters=self.request.params.mixed()) message = '&'.join(( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), )) local_hash = hashlib.sha1(message).digest() # Apply the public key to the signature from the remote host sig = base64.decodestring( urllib.unquote(self.request.params.mixed()["oauth_signature"])) remote_hash = public_key.encrypt(sig, '')[0][-20:] # Verify that the locally-built value matches the value from the remote server. if local_hash == remote_hash: return True else: return False
def complete_parameters(self, url, params={}, exclude_signature=[]): defaults = { 'oauth_timestamp': str(int(time.time())), 'oauth_nonce': oauth.generate_nonce(), 'signature_method': "HMAC-SHA1", 'oauth_token': self.access_token.key, 'oauth_consumer_key': self.consumer.key, } excluded = {} for e in exclude_signature: excluded[e] = params.pop(e) defaults.update(params) req = oauth.OAuthRequest(http_method="POST", http_url=url, parameters=defaults) req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, self.access_token) req.parameters.update(excluded) return req
def oauth_get_request_token(oaConsumer, url): '''Get an OAuth request token URL to use for verification. Returns a tuple of (token, url). The 'url' parameter indicates the destination for redirection once the user has validated the request.''' oaSig = oauth.OAuthSignatureMethod_HMAC_SHA1() oaReq = oauth.OAuthRequest( http_method = 'GET', http_url = OAUTH2_ENDPOINT_URL + '/get_request_token', parameters = { 'oauth_nonce' : oauth.generate_nonce(), 'oauth_timestamp' : oauth.generate_timestamp(), 'oauth_consumer_key' : oaConsumer.key, 'oauth_version' : '1.0', 'xoauth_lang_pref' : 'en-us', 'oauth_callback' : url, } ) oaReq.sign_request(oaSig, oaConsumer, None) reqTokenResp = None try: reqTokenResp = urllib2.urlopen(oaReq.to_url()) reqTokenRespContent = ''.join(reqTokenResp.readlines()) oaReqToken = oauth.OAuthToken.from_string(reqTokenRespContent) return ( oaReqToken, OAUTH2_ENDPOINT_URL + '/request_auth?' + urllib.urlencode([('oauth_token', oaReqToken.key)]) ) except urllib2.HTTPError, e: raise CascadeHTTPError(e)
def make_signed_req(self, url, method='GET', content={}, headers={}, token=None, request=None): """ Identical to the make_request API, and accepts an additional (optional) token parameter and request object (required if dealing with Scalable OAuth service providers). It adds the OAuth Authorization header based on the consumer set on this instance. If content not a Mapping object, it will be ignored with respect to signing. This means you need to either pass the query parameters as a dict/Mapping object, or pass a encoded query string as part of the URL which will be extracted and included in the signature. http://oauth.net/core/1.0/#rfc.section.7 Arguments: `url` The URL - query parameters will be parsed out. `method` The HTTP method to use. `content` A dict of key/values or string/unicode value. `headers` A dict of headers. `token` An optional access token. If this is provided, you will be making a 3-legged request. If it is missing, you will be making a 2-legged request. `request` *Optional*. Needed if using Scalable OAuth in order to transparently handle access token renewal. http://wiki.oauth.net/ScalableOAuth#AccessTokenRenewal """ if isinstance(content, collections.Mapping): params = content else: params = {} orequest = oauth.OAuthRequest(url, method, params) orequest.sign_request(self.sig_method, self.consumer, token) headers['Authorization'] = orequest.to_header(self.realm) response = make_request(url, method=method, content=content, headers=headers) # check if we got a scalable oauth token_expired error # we will fetch a new access token using the oauth_session_handle in # the current token and redo the request in this case. # FIXME: infinite loop www_auth = response.getheader('www-authenticate', None) if www_auth and response.status == 401 and 'token_expired' in www_auth: response = self.make_signed_req(self.access_token_url, content={ 'oauth_session_handle': token['oauth_session_handle'] }, token=token, request=request) body = unicode(response.read(), 'utf8').strip() new_token = urlencoding.parse_qs(body) self.store_access_token(request, new_token) return self.make_signed_req(url, method, content, headers, new_token, request) else: return response
def user_authorize(self): defaults = hidden.keys().copy() defaults["oauth_timestamp"] = oauth.generate_timestamp() defaults["oauth_nonce"] = oauth.generate_nonce() defaults["oauth_signature_method"] = "HMAC-SHA1" defaults["oauth_version"] = "1.0" defaults["oauth_callback"] = "https://www.flickr.com/" # Setup the consumer with api_key and api_secret consumer = oauth.OAuthConsumer(defaults["oauth_consumer_key"], defaults["oauth_consumer_secret"]) # Create request oauth_req = oauth.OAuthRequest(http_method="GET", http_url=self.url_req_token, parameters=defaults) # Create signature oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None) url = oauth_req.to_url() print '* Calling Flickr...' print connection = urllib.urlopen(url) data = connection.read() request_token = { "oauth_token": re.findall("oauth_token=(.+)&", data)[0], "oauth_token_secret": re.findall("oauth_token_secret=(.+)", data)[0] } #print request_token token = oauth.OAuthToken(request_token["oauth_token"], request_token["oauth_token_secret"]) print "Go to the following link in your browser:" print "http://www.flickr.com/services/oauth/authorize?oauth_token=%s&perms=read" % request_token[ 'oauth_token'] print oauth_verifier = raw_input("Enter the verifier - ") print defaults["oauth_token"] = request_token["oauth_token"] defaults["oauth_verifier"] = oauth_verifier del defaults["oauth_consumer_secret"] oauth_req = oauth.OAuthRequest(http_method="GET", http_url=self.url_access_token, parameters=defaults) oauth_req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) url = oauth_req.to_url() connection = urllib.urlopen(url) data = connection.read() defaults["oauth_token"] = re.findall("oauth_token=(.+?)&", data)[0] defaults["oauth_token_secret"] = re.findall( "oauth_token_secret=(.+?)&", data)[0] defaults["username"] = re.findall("username=(.+)", data)[0] defaults["user_nsid"] = re.findall("user_nsid=(.+?)&", data)[0] self.tokens["token"] = defaults["oauth_token"] self.tokens["token_secret"] = defaults["oauth_token_secret"] # Replace %40 in user_id, or the request url would be wrong if "%40" in defaults["user_nsid"]: self.user_id = defaults["user_nsid"].replace("%40", "@") print self.user_id else: self.user_id = defaults["user_nsid"] cur.execute('''INSERT INTO Tokens (token, secret) VALUES (?, ?)''', (defaults["oauth_token"], defaults["oauth_token_secret"])) # Named placeholders style cur.execute('SELECT id FROM Tokens WHERE token=:t AND secret=:ts', { "t": defaults["oauth_token"], "ts": defaults["oauth_token_secret"] }) token_id = cur.fetchone()[0] # Store username in database cur.execute( ''' INSERT OR IGNORE INTO Users (name, token_id, user_id) VALUES (?, ?, ?)''', (defaults["username"], token_id, self.user_id)) conn.commit()
def test_url_with_query_string(self): request = oauth.OAuthRequest('http://daaku.org/?a=1') self.assertEqual(request.url, 'http://daaku.org/') self.assertEqual(request.params, {'a': '1'})
def createOAuthRequest(commandLineOptions, commandArguments): # Create an empty request object oAuthRequest = oauth.OAuthRequest() # Store the oauth_method to be used oAuthRequest.oauth_method = commandLineOptions.oauth_method # Set the HTTP method to use (this instance variable is used as part of the base signature string) if (commandLineOptions.oauth_method == "header" or commandLineOptions.oauth_method == "GET"): oAuthRequest.http_method = "GET" else: oAuthRequest.http_method = "POST" # Set the URL end point if (len(commandArguments) == 1): oAuthRequest.http_url = commandArguments[0] else: oAuthToolLogger.error( "Error: Final command line argument must be a URL endpoint") sys.exit(1) # Create an OAuth consumer object and store it in the oAuthRequest object oAuthRequest.consumer = oauth.OAuthConsumer( key=commandLineOptions.oauth_consumer_key, secret=commandLineOptions.oauth_consumer_secret) # Create an OAuthToken object if (commandLineOptions.oauth_tokenkey != None and commandLineOptions.oauth_tokensecret != None): oAuthRequest.token = oauth.OAuthToken( key=commandLineOptions.oauth_tokenkey, secret=commandLineOptions.oauth_tokensecret) else: oAuthRequest.token = None # Clear out the oAuthRequest's parameters dictionary and populate it manually oAuthRequest.parameters = {} oAuthRequest.parameters['oauth_consumer_key'] = oAuthRequest.consumer.key oAuthRequest.parameters['oauth_version'] = '1.0' # Use a specific timestamp if given if (commandLineOptions.oauth_timestamp != None): oAuthRequest.parameters[ 'oauth_timestamp'] = commandLineOptions.oauth_timestamp else: oAuthRequest.parameters['oauth_timestamp'] = calendar.timegm( time.gmtime(time.time())) # Use a specific nonce if given if (commandLineOptions.oauth_nonce != None): oAuthRequest.parameters['oauth_nonce'] = commandLineOptions.oauth_nonce else: oAuthRequest.parameters['oauth_nonce'] = hashlib.sha224( str(oAuthRequest.parameters['oauth_timestamp'])).hexdigest() if (commandLineOptions.oauth_callback != None): oAuthRequest.parameters[ 'oauth_callback'] = commandLineOptions.oauth_callback # The token parameter is only used in certain instances if (oAuthRequest.token != None): oAuthRequest.parameters['oauth_token'] = oAuthRequest.token.key # Determine which signature method to use if (commandLineOptions.oauth_signature_method == "HMAC-SHA1"): signatureMethod = oauth.OAuthSignatureMethod_HMAC_SHA1() elif (commandLineOptions.oauth_signature_method == "RSA-SHA1"): pass elif (commandLineOptions.oauth_signature_method == "PLAINTEXT"): signatureMethod = oauth.OAuthSignatureMethod_PLAINTEXT() else: oAuthToolLogger.error( "Unknown signature method. Please specify one of HMAC-SHA1, RSA-SHA1, or PLAINTEXT" ) sys.exit( "Unknown signature method. Please specify one of HMAC-SHA1, RSA-SHA1, or PLAINTEXT" ) # Calculate the signature (this will store it in oauth_signature) oAuthRequest.sign_request(signatureMethod, oAuthRequest.consumer, oAuthRequest.token) oAuthToolLogger.debug("Calculated signature: " + str(oAuthRequest.parameters['oauth_signature'])) return oAuthRequest
def oauth_get_access_token(oaConsumer, oaReqToken): '''Get an OAuth access token from the given token (either request or access). Returns an oauth.OAuthToken, possibly with some extra instance variables set to reflect presence of OAuth extension attributes in the response (e.g. session handle, expiration time, etc). Can be called with an access token to attempt a refresh (which still returns a new token).''' oaSig = oauth.OAuthSignatureMethod_HMAC_SHA1() oaReqParams = { 'oauth_nonce' : oauth.generate_nonce(), 'oauth_timestamp' : oauth.generate_timestamp(), 'oauth_consumer_key' : oaConsumer.key, 'oauth_token' : oaReqToken.key, 'oauth_version' : '1.0', } # If our token has a session handle, add it to our parmeter dictionary. # This should only be the case if we're requesting a new access token # (i.e. not doing a token refresh, as access tokens do not have a # verifier). if 'verifier' in oaReqToken.__dict__: oaReqParams['oauth_verifier'] = oaReqToken.verifier # If our token has a session handle, add it to our parmeter dictionary. # This should only be the case if we're doing a token refresh from an # access token. if 'session_handle' in oaReqToken.__dict__: oaReqParams['oauth_session_handle'] = oaReqToken.session_handle oaReq = oauth.OAuthRequest( http_method = 'GET', http_url = OAUTH2_ENDPOINT_URL + '/get_token', parameters = oaReqParams ) oaReq.sign_request(oaSig, oaConsumer, oaReqToken) accTokenResp = None try: accTokenResp = urllib2.urlopen(oaReq.to_url()) accTokenRespContent = ''.join(accTokenResp.readlines()) accTok = oauth.OAuthToken.from_string(accTokenRespContent) # Look for any extra query parameters that provide data from OAuth # extensions that we might care about. Specifically, make sure to # grab the session handle so that we can refresh the access token. accTokParams = cgi.parse_qs( accTokenRespContent, keep_blank_values = False ) if 'oauth_expires_in' in accTokParams: accTok.expires_on = \ int(time.time()) + \ int(accTokParams['oauth_expires_in'][0]) if 'oauth_session_handle' in accTokParams: accTok.session_handle = accTokParams['oauth_session_handle'][0] if 'oauth_authorization_expires_in' in accTokParams: accTok.authorization_expires_on = \ int(time.time()) + \ int(accTokParams['oauth_authorization_expires_in'][0]) if 'xoauth_yahoo_guid' in accTokParams: accTok.yahoo_guid = accTokParams['xoauth_yahoo_guid'][0] return accTok except urllib2.HTTPError, e: raise CascadeHTTPError(e)
def call(self, method, params = [{}], id = None, oauthDefaults = {}): '''Call the given method using the specified parameters (which are passed directly as the 'params' value in the JSON payload). Returns a result object derived from un-serializing the response JSON data. The optional 'id' value is the Cascade call ID, which is not sent in the request if un-specified. The 'oauthDefaults' dictionary can be used to specify default OAuth parameter values. For example, one can use this to force a specific nonce or timestamp value. Any parameters not specifed in this dictionary fall back to their OAuth defaults (e.g. generate a new nonce). Raises a CascadeHTTPError if problems arise.''' # Populate OAuth parameters oauthParameters = { 'oauth_nonce' : oauth.generate_nonce(), 'oauth_timestamp' : oauth.generate_timestamp(), 'oauth_consumer_key' : self.__oaConsumer.key, 'oauth_version' : '1.0' } oauthParameters.update(oauthDefaults) # Populate Cascade parameters data = { 'method' : method, 'params' : params } if id: data['id'] = id data = simplejson.dumps(data) for attemptNo in range(0, 2): logging.debug('Making request %d / 2' % (attemptNo + 1)) # Set the token every time through our loop, as we may have changed # our token due to it being stale oauthParameters['oauth_token'] = self.__oaToken.key # Construct and sign the request within our retry loop so that # we pick up any refresh of the access token oaReq = oauth.OAuthRequest( http_method = 'POST', http_url = JSON11_ENDPOINT_URL, parameters = oauthParameters ) oaReq.sign_request(self.__oaSig, self.__oaConsumer, self.__oaToken) headers = { 'Content-Type' : 'application/json' } url = JSON11_ENDPOINT_URL if self.__sendAuthorizationHeader: headers.update(oaReq.to_header()) else: url = oaReq.to_url() logging.debug('HTTP headers: ' + pprint.pformat(headers)) cascadeResp = None try: cascadeReq = urllib2.Request( url = url, data = data, headers = headers ) cascadeResp = urllib2.urlopen(cascadeReq) return simplejson.loads(''.join(cascadeResp.readlines())) except urllib2.HTTPError, e: logging.info( 'HTTP request failed: code=%d; message=\'%s\'' % ( e.code, e.msg ) ) # If we see something other than a 401 on our first attempt # to make the call, give up. Otherwise, attempt to refresh # our access token and try again. if attemptNo > 0 or e.code != 401: raise CascadeHTTPError(e) logging.info('Refreshing OAuth access token ' + self.__oaToken.key) self.__oaToken = oauth_refresh_access_token( self.__oaConsumer, self.__oaToken ) logging.info('New OAuth access token is ' + self.__oaToken.key) finally:
def test_params_as_string(self): request = oauth.OAuthRequest('http://daaku.org/', params='a=1') self.assertEqual(request.url, 'http://daaku.org/') self.assertEqual(request.params, {'a': '1'})