def perform_API_request(site, uri, method, key, secret, consumer_key): resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % (secret, key) resource_token = oauth.OAuthToken.from_string(resource_tok_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=site, parameters={'oauth_nonce': uuid.uuid4().hex}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() url = "%s%s" % (site, uri) http = httplib2.Http() return http.request(url, method, body=None, headers=headers) # API key = '<consumer_key>:<key>:<secret>' # response = perform_API_request( # 'http://192.168.3.51/MAAS/api/2.0', '/nodes/?op=list', 'GET', 'FmLaaNZjXQUf76qC5E', '4bbAQaP9aqhSK7JrrdKLKF5qpLynPHSc', # 'Rm9L8J3cwfmt5WZe9V') # # print(response)
def __init__(self): """Create the objects we need to connect to an OAuth server""" self.connection = httplib.HTTPConnection(API_SERVER) self.connection.set_debuglevel(100) self.consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
def do_oauth(weibo_type): config = ConfigParser.ConfigParser() config.read('config.ini') #get config server = config.get(weibo_type, 'server') port = config.getint(weibo_type, 'port') request_token_url = config.get(weibo_type, 'request_token_url') authorize_url = config.get(weibo_type, 'authorize_url') access_token_url = config.get(weibo_type, 'access_token_url') app_key = config.get(weibo_type, 'app_key') app_secret = config.get(weibo_type, 'app_secret') callback_url = config.get('common', 'callback_url') #setup client = BaseOAuthClient(server, port, request_token_url, access_token_url, authorize_url) consumer = oauth.OAuthConsumer(app_key, app_secret) signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, callback=callback_url, http_url=client.request_token_url) oauth_request.sign_request(signature_method_hmac_sha1, consumer, None) print 'REQUEST (via headers)' print 'parameters: %s' % str(oauth_request.parameters) 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)
def get_access_token(self): connection = httplib.HTTPSConnection('api.login.yahoo.com') signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() # Step 1: Get a Request Token oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, callback='oob', http_url=token_url) oauth_request.sign_request(signature_method, self.consumer, None) connection.request(oauth_request.http_method, token_url, headers=oauth_request.to_header()) response = connection.getresponse().read() request_token = oauth.OAuthToken.from_string(response) # Step 2: Get User Authorization print('Go to: {0}?oauth_token={1}'.format(auth_url, request_token.key)) verifier = raw_input('Verification code: ') # Step 3: Exchange Request Token and Verifier for Access Token oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, request_token, verifier=verifier, http_url=access_url) oauth_request.sign_request(signature_method, self.consumer, request_token) connection.request(oauth_request.http_method, access_url, headers=oauth_request.to_header()) response = connection.getresponse().read() params = cgi.parse_qs(response, keep_blank_values=False) self.session_handle = params['oauth_session_handle'][0] self.access_token = oauth.OAuthToken.from_string(response)
def __init__(self, consumer_key, consumer_secret, access_type, locale=None): """Initialize a DropboxSession object. Your consumer key and secret are available at https://www.dropbox.com/developers/apps Args: access_type: Either 'dropbox' or 'app_folder'. All path-based operations will occur relative to either the user's Dropbox root directory or your application's app folder. locale: A locale string ('en', 'pt_PT', etc.) [optional] The locale setting will be used to translate any user-facing error messages that the server generates. At this time Dropbox supports 'en', 'es', 'fr', 'de', and 'ja', though we will be supporting more languages in the future. If you send a language the server doesn't support, messages will remain in English. Look for these translated messages in rest.ErrorResponse exceptions as e.user_error_msg. """ assert access_type in [ 'dropbox', 'app_folder' ], "expected access_type of 'dropbox' or 'app_folder'" self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.token = None self.request_token = None self.signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() self.root = 'sandbox' if access_type == 'app_folder' else 'dropbox' self.locale = locale
def __init__(self, consumer, token, sig_method=oauth.OAuthSignatureMethod_PLAINTEXT()): self.consumer = consumer self.token = token self.sig_method = sig_method
def yahoo(self, title=None, analyze=True, start='0'): q = title if title is None and request: q = request.args['q'] if start == "0" and request: start = request.args['start'] if request and request.args.get("analyze", {}) == "false": analyze = False URL = "http://yboss.yahooapis.com/ysearch/news" OAUTH_CONSUMER_KEY = "dj0yJmk9RHp0ckM1NnRMUmk1JmQ9WVdrOVdUbHdOMkZLTTJVbWNHbzlNakV5TXpReE1EazJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0xMg--" OAUTH_CONSUMER_SECRET = "626da2d06d0b80dbd90799715961dce4e13b8ba1" pr("here") data = { "q": q, "start": start, "sort": "date", "age": "1000d", "format":"json" } consumer = oauth.OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET) signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=None, http_method='GET', http_url=URL, parameters=data) oauth_request.sign_request(signature_method_hmac_sha1, consumer, "") complete_url = oauth_request.to_url() response = urllib.urlopen(complete_url).read() stories = json.loads(response).get("bossresponse").get("news", {}).get("results") if stories is not None: for story in stories: normalize(story, self.normalizers['yahoo']) if analyze is True: analyzeStory(story) return json.dumps(stories, default=dthandler)
def __init__(self, server, port=80, path='', consumer_key='', consumer_secret='', https=False): self.server, self.port = server, port self.path = path self.consumer_key, self.consumer_secret = consumer_key, consumer_secret self.request_token_url = self.REQUEST_TOKEN_URL self.access_token_url = self.ACCESS_TOKEN_URL self.authorization_url = self.AUTHORIZATION_URL if https: self.connection = httplib.HTTPSConnection('%s:%d' % (self.server, self.port)) else: self.connection = httplib.HTTPConnection("%s:%d" % (self.server, self.port)) self.consumer = oauth.OAuthConsumer(self.consumer_key, self.consumer_secret) self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT( ) self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1( )
def __init__(self, *args, **kwargs): self.oauth_server = oauth.OAuthServer(MockOAuthDataStore()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def _dispatch(self, uri, method, body=None): body = self._validate_verb(method, body) resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % ( self.secret, self.key) resource_token = oauth.OAuthToken.from_string(resource_tok_string) consumer_token = oauth.OAuthConsumer(self.consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=self.maas_url, parameters={'oauth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() url = "%s%s" % (self.maas_url, uri) http = httplib2.Http() LOG.debug("Sending request to: %s" % url) response, content = http.request(url, method, body=body, headers=headers) self._check_response(response) body = json.loads(content) return body
def __init__(self): realm = config.get("tools.oauth.realm", "http://www.example.com") datastore_class_path = config.get( "tools.oauth.datastore", "gearshift.tools.oauth.sodatastore.OAuthDataStore") datastore_class = load_class(datastore_class_path) if datastore_class: log.info("Successfully loaded \"%s\"" % datastore_class_path) else: log.error("Unable to load \"%s\"" % datastore_class_path) return self.datastore = datastore_class() self.request_token_url = config.get('oauth.request_token.url', '/request_token') self.access_token_url = config.get('oauth.access_token.url', '/access_token') self.realm = realm self.oauth_server = oauth.OAuthServer(self.datastore) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) log.info("OAuthTool initialized") return super(OAuthTool, self).__init__(point='before_handler', callable=self.before_handler, priority=10)
def setup(client, consumer): """ Get everything ready to make requests """ signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() # Get Request Token oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_url=client.request_token_url) oauth_request.sign_request(signature_method_plaintext, consumer, None) token = client.fetch_request_token(oauth_request) # Authorize token url = client.authorization_url #.replace("$REQUEST_TOKEN", token.key) oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, http_url=url) response = client.authorize_token(oauth_request) import urlparse query = urlparse.urlparse(response)[4] params = urlparse.parse_qs(query, keep_blank_values=False) verifier = params['oauth_verifier'][0] # Get Access Token oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, verifier=verifier, http_url=client.access_token_url) oauth_request.sign_request(signature_method_plaintext, consumer, token) token = client.fetch_access_token(oauth_request) return token
def __init__(self): self.consumers = {} """A dictionary of :class:`BLTIConsumer` instances keyed on the consumer key.""" self.oauth_server = oauth.OAuthServer(self) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1())
def oauth_server(self): if not hasattr(self, '_oauth_server'): self._oauth_server = oauth.OAuthServer(OAuthDataStore()) self._oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self._oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) return self._oauth_server
def main(): connection = httplib.HTTPSConnection(SERVER) consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) ''' Fitbit API doesn't accept hmac-sha1; use plain text ''' #signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() if DEBUG: print '* Reading file', ACCESS_TOKEN_STRING_FNAME fobj = open(ACCESS_TOKEN_STRING_FNAME) access_token_string = fobj.read() fobj.close() access_token = oauth.OAuthToken.from_string(access_token_string) # Grab incoming info from text messages from_number = request.form['From'] todays_weight = request.form['Body'] mydate = date.today().isoformat() if from_number in config.callers and is_number(todays_weight) == True: # reply to the user by sms message = "Hi " + config.callers[str( from_number)] + "! Got it, " + str(todays_weight) + " today." twilio_response = create_sms(message) if DEBUG: print "* SMS ready" # post info to fitbit weight_info = {'weight': to_kg(todays_weight), 'date': mydate} params = urllib.urlencode(weight_info) url = '/1/user/-/body/log/weight.xml' apiCall = url + '?' + params if DEBUG: print "* submitting to url " + apiCall # access protected resource oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=access_token, http_url=apiCall) oauth_request.sign_request(signature_method, consumer, access_token) headers = oauth_request.to_header(realm='api.fitbit.com') connection.request('POST', apiCall, headers=headers) fitbitresp = connection.getresponse() xml = fitbitresp.read() print "* SUCCESS! Data logged at Fitbit: " + xml elif from_number not in config.callers: message = "Sorry, you can't update Fitbit from this number: " + str( from_number) twilio_response = create_sms(message) else: message = "Nice try buddy. That wasn't a valid number." twilio_response = create_sms(message) if DEBUG: print "* Sending SMS" return str(twilio_response)
def __init__(self, server, consumer_key, consumer_secret, access_token_fsp, request_token_url, auth_url, access_token_url, realm): self.connection = httplib.HTTPSConnection(server) self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() self.access_token_fsp = access_token_fsp self.request_token_url = request_token_url self.auth_url = auth_url self.access_token_url = access_token_url self.realm = realm self.access_token = self.get_access_token()
def sign_request(self, url, headers): """Sign a request. @param url: The URL to which the request is to be sent. @param headers: The headers in the request. These will be updated with the signature. """ oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer_token, token=self.resource_token, http_url=url) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), self.consumer_token, self.resource_token) headers.update(oauth_request.to_header())
def __init__(self, api_server, consumer_key, consumer_secret, debug=100): """Create the objects we need to connect to an OAuth server""" self.api_server = api_server oauth_server_path = 'http://%s/oauth' % api_server self.request_token_url = oauth_server_path + '/request_token/' self.access_token_url = oauth_server_path + '/access_token/' self.authorization_url = oauth_server_path + '/authorize/' self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT( ) self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1( )
def verify_request_common(consumers, url, method, headers, params): """ Verifies that request is valid :param consumers: consumers from config file :param url: request url :param method: request method :param headers: request headers :param params: request params :return: is request valid """ log.debug("consumers %s", consumers) log.debug("url %s", url) log.debug("method %s", method) log.debug("headers %s", headers) log.debug("params %s", params) oauth_store = LTIOAuthDataStore(consumers) oauth_server = oauth.OAuthServer(oauth_store) oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) # Check header for SSL before selecting the url if headers.get('X-Forwarded-Proto', 'http') == 'https': url = url.replace('http:', 'https:', 1) oauth_request = oauth.OAuthRequest.from_request( method, url, headers=dict(headers), parameters=params ) if not oauth_request: log.info('Received non oauth request on oauth protected page') raise LTIException('This page requires a valid oauth session ' 'or request') try: # pylint: disable=protected-access consumer = oauth_server._get_consumer(oauth_request) oauth_server._check_signature(oauth_request, consumer, None) except oauth.OAuthError as e: print("ERR", e.message) # Rethrow our own for nice error handling (don't print # error message as it will contain the key raise LTIException("OAuth error: Please check your key and secret") return True
def GetAccessToken(self, access_code, auth_token): oauth_verifier = access_code connection = httplib.HTTPSConnection(self.SERVER) consumer = oauth.OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=auth_token, http_url=self.ACCESS_TOKEN_URL, parameters={'oauth_verifier': oauth_verifier}) oauth_request.sign_request(signature_method, consumer, auth_token) # now the token we get back is an access token # parse the response into an OAuthToken object access_token = oauth.OAuthToken.from_string(self.FetchResponse(oauth_request,connection)) # store the access token when returning it access_token = access_token.to_string() return access_token
def oauth_headers(url, consumer_key, token_key, token_secret, consumer_secret): consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) token = oauth.OAuthToken(token_key, token_secret) params = { 'oauth_version': "1.0", 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': int(time.time()), 'oauth_token': token.key, 'oauth_consumer_key': consumer.key, } req = oauth.OAuthRequest(http_url=url, parameters=params) req.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer, token) return(req.to_header())
def __make_api_call_json(self, apiCall): connection = httplib.HTTPSConnection(self.SERVER) consumer = oauth.OAuthConsumer(self.consumer_key, self.consumer_secret) signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() token = self.get_token_string() access_token = oauth.OAuthToken.from_string(token) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=access_token, http_url=apiCall) oauth_request.sign_request(signature_method, consumer, access_token) headers = oauth_request.to_header(realm='api.fitbit.com') connection.request('GET', apiCall, headers=headers) resp = connection.getresponse() j_data = resp.read() return json.loads(j_data)
def GetRequestToken(self): connection = httplib.HTTPSConnection(self.SERVER) consumer = oauth.OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, http_url=self.REQUEST_TOKEN_URL) oauth_request.sign_request(signature_method, consumer, None) resp = self.FetchResponse(oauth_request, connection) auth_token = oauth.OAuthToken.from_string(resp) #build the URL authkey = str(auth_token.key) authsecret = str(auth_token.secret) auth_url = "%s?oauth_token=%s" % (self.AUTHORIZATION_URL, auth_token.key) return auth_url, auth_token
def perform_API_request(site, uri, method, key, secret, consumer_key): resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % (secret, key) resource_token = oauth.OAuthToken.from_string(resource_tok_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=site, parameters={'oauth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() url = "%s%s" % (site, uri) return requests.get(url, headers=headers)
def auth(self): # Split the token from MaaS (Maas UI > username@domain > Account > MaaS Keys) into its component parts (consumer_key, key, secret) = self.token.split(':') # Format an OAuth header resource_token_string = "oauth_token_secret=%s&oauth_token=%s" % ( secret, key) resource_token = oauth.OAuthToken.from_string(resource_token_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=self.maas, parameters={'auth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() return headers
def refresh_access_token(self): print('Refreshing access token...') connection = httplib.HTTPSConnection('api.login.yahoo.com') signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, self.access_token, http_url=access_url) oauth_request.set_parameter('oauth_session_handle', self.session_handle) oauth_request.sign_request(signature_method, self.consumer, self.access_token) connection.request(oauth_request.http_method, access_url, headers=oauth_request.to_header()) response = connection.getresponse().read() params = cgi.parse_qs(response, keep_blank_values=False) self.session_handle = params['oauth_session_handle'][0] self.access_token = oauth.OAuthToken.from_string(response)
def call(access_token, endpoint): signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() connection = httplib.HTTPSConnection(SERVER) #build the access token from a string access_token = oauth.OAuthToken.from_string(access_token) consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=access_token, http_url=endpoint) oauth_request.sign_request(signature_method, consumer, access_token) headers = oauth_request.to_header(realm='api.fitbit.com') connection.request('GET', endpoint, headers=headers) resp = connection.getresponse() result = resp.read() return json.loads(result)
def auth(): global maas, token, args (consumer_key, key, secret) = token.split(':') # Format an OAuth header resource_token_string = "oauth_token_secret=%s&oauth_token=%s" % (secret, key) resource_token = oauth.OAuthToken.from_string(resource_token_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=maas, parameters={'auth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() return headers
def get_auth_headers(self, url, params, http_method): """Get authentication headers to be sent with the request. @param url: The URL being requested. @param params: A {dict} of quesry string parameters @param http_method: The HTTP Method being used. """ consumer, token = self.get_consumer_and_token() oauth_req = oauth.OAuthRequest.from_consumer_and_token( http_url=url, http_method=http_method, token=token, oauth_consumer=consumer, parameters=params) # using PLAINTEXT, because HMAC doesn't work for all urls signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() oauth_req.sign_request(signature_method, consumer, token) return oauth_req.to_header()
def auth(self): """Split the user's API key from MAAS into its component parts (Maas UI > Account > MAAS Keys).""" (consumer_key, key, secret) = self.token.split(':') # Format an OAuth header resource_token_string = "oauth_token_secret={}&oauth_token={}".format( secret, key) resource_token = oauth.OAuthToken.from_string(resource_token_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=self.maas, parameters={'auth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() headers['Accept'] = 'application/json' return headers