I am working on a module for an application written in Python (it is open-source). I want the module to allow a user to log into Twitter and update status (post a tweet). I have Python script I wrote using the twitter import that requires a developer (me) to put in consumer/authentication token/secrets. I don't want to have the tokens pre-programmed into the module, but rather have a user log in to update THEIR status (obviously).
I need a general direction to pursue. I envision the user clicking on a Share! menu option, a browser popping up with the Twitter login page, a user logging in and the application storing the credentials, and then updating the status from there. I have the module working, but like I said before, I need to input token information from my application's apps.twitter.com page. I want the user to be able to log in.
Here is a snip of code using the twython library:
from twython import Twython
#APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET
OAUTH_TOKEN = '...'
OAUTH_TOKEN_SECRET = '...'
APP_KEY = '...'
APP_SECRET = '...'
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
if (twitter.update_status(status='The status is updated from Python!')):
print("Working!")
else:
print("Not working!")
The code above works and updates my Twitter status, but I do not want other users of this module to be updating my status, but rather have them log in and update their status.
Thanks in advance.
EDIT
What I have now:
import urllib.parse
import oauth2 as oauth
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
authorize_url = 'https://api.twitter.com/oauth/authorize'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
request_token = dict(urllib.parse.parse_qsl(content))
print("Request Token:")
print(" - oauth_token = %s" % request_token[b'oauth_token'].decode())
print(" - oauth_token_secret = %s" % request_token[b'oauth_token_secret'].decode())
print("Go to the following link in your browser:")
print("%s?oauth_token=%s" % (authorize_url, request_token[b'oauth_token'].decode()))
accepted = 'n'
while accepted.lower() == 'n':
accepted = input('Have you authorized me? (y/n) ')
oauth_verifier = input('What is the PIN? ')
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(urllib.parse.parse_qsl(content))
print(access_token.keys())
print(access_token.values())
print("You may now access protected resources using the access tokens above.")
import twitter
api = twitter.Api(consumer_key=' ', consumer_secret=' ',
access_token_key=' ', access_token_secret=' ')
tweet = api.PostUpdate("First tweet from an authenticated user.")
I get to the point where I authorize my application with the login, the webpage redirects to the callback_url, just like it should, but I don't get a PIN to input. Where does that come in?
i know it late but it can be help others
you can find verify token after your app verify and it will be show into header.
Related
I'm currently trying to get the Twitter API to work using either Tweepy or Twython.
My code looks like this :
#-------------------TWEEPY------------------------
APP_KEY = os.getenv("APP_KEY")
APP_SECRET = os.getenv("APP_SECRET")
auth = tweepy.OAuthHandler(APP_KEY, APP_SECRET,callback="https://www.google.com/")
url=auth.get_authorization_url()
webbrowser.open(url)
token = auth.get_access_token(verifier = "Don't know how to get")
#-------------------TWYTHON------------------------
APP_KEY = os.getenv("APP_KEY")
APP_SECRET = os.getenv("APP_SECRET")
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=1)
auth = twitter.get_authentication_tokens(force_login=True,callback_url="https://www.google.com/")
twitter = Twython(APP_KEY, APP_SECRET,auth['oauth_token'], auth['oauth_token_secret'])
webbrowser.open(auth['auth_url'])
oauth_verifier_url = auth['auth_url']
oauth_verifier = requests.get(auth['auth_url'])
final_step = twitter.get_authorized_tokens("Don't know how to get")
I am currently stuck and facing two issues.
The first only happens sometime when I use
url=auth.get_authorization_url() #WITH TWEEPY
or
twitter = Twython(APP_KEY, APP_SECRET,auth['oauth_token'], auth['oauth_token_secret']) #WITH TWYTHON
Sometime I get this error (maybe because I'm calling to muchthe API) :
TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}]
But sometime it work and i facing an other problem :
How can I get the "oauth_verifier"?
I set the redirect address on google
It will return something like this and I really want to get the "oauth_verifier" without having to ask the user.
Does anyone have a solution or a clue?
I am writing an OAuth for Jira. But I get the error "Password was not given but the private key is encrypted". I was also trying to implement this solution with js but sadly it didn't work. Now I am trying with python.
I want to call a Jira Rest API, and for that I need the oAuth (in order to create jira tickets via code).
My Code is:
import requests
from oauthlib.oauth1 import SIGNATURE_RSA
from requests_oauthlib import OAuth1Session
from jira.client import JIRA
def read(file_path):
#""" Read a file and return it's contents. """
with open(file_path) as f:
return f.read()
# The Consumer Key created while setting up the "Incoming Authentication" in
# JIRA for the Application Link.
CONSUMER_KEY = ('myconsumerkey')
# The contents of the rsa.pem file generated (the private RSA key)
RSA_KEY = read('myfilelink')
# The URLs for the JIRA instance
JIRA_SERVER = 'myjiralink'
REQUEST_TOKEN_URL = JIRA_SERVER + '/plugins/servlet/oauth/request-token'
AUTHORIZE_URL = JIRA_SERVER + '/plugins/servlet/oauth/authorize'
ACCESS_TOKEN_URL = JIRA_SERVER + '/plugins/servlet/oauth/access-token'
# Step 1: Get a request token
oauth = OAuth1Session(CONSUMER_KEY, signature_type='auth_header',
signature_method=SIGNATURE_RSA, rsa_key=RSA_KEY)
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
print("STEP 1: GET REQUEST TOKEN")
print(" oauth_token={}".format(request_token['oauth_token']))
print(" oauth_token_secret={}".format(request_token['oauth_token_secret']))
print("\n")
# Step 2: Get the end-user's authorization
print("STEP2: AUTHORIZATION")
print(" Visit to the following URL to provide authorization:")
print(" {}?oauth_token={}".format(AUTHORIZE_URL, request_token['oauth_token']))
print("\n")
while input("Press any key to continue..."):
pass
# Step 3: Get the access token
access_token = oauth.fetch_access_token(ACCESS_TOKEN_URL)
print("STEP2: GET ACCESS TOKEN")
print(" oauth_token={}".format(access_token['oauth_token']))
print(" oauth_token_secret={}".format(access_token['oauth_token_secret']))
print("\n")
# Now you can use the access tokens with the JIRA client. Hooray!
jira = JIRA(options={'server': JIRA_SERVER}, oauth={
'access_token': access_token['oauth_token'],
'access_token_secret': access_token['oauth_token_secret'],
'consumer_key': CONSUMER_KEY,
'key_cert': RSA_KEY
})
# print all of the project keys just as an exmaple
for project in jira.projects():
print(project.key)
I solved the issue. The problem was that the private key was password protected. I removed, for now, the protection and it works.
The next step would be to authenticate with the password-private-key, but that is another question. I will mark this problem as solved.
How do I get these keys from LinkedIn?
OAUTH_TOKEN and OAUTH_TOKEN_SECRET
When I register my application on LinkedIn Developer, I'm only getting:
CONSUMER_KEY, CONSUMER_SECRET
I have two Python functions which require it.
E.g. -
from linkedin import linkedin # pip install python-linkedin
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
USER_TOKEN = ''
USER_SECRET = ''
RETURN_URL = '' # Not required for developer authentication
# Instantiate the developer authentication class
auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL,
permissions=linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
app = linkedin.LinkedInApplication(auth)
# Use the app...
app.get_profile()
and
#!/usr/bin/env python
# encoding: utf-8
"""
linkedin-2-query.py
Created by Thomas Cabrol on 2012-12-03.
Copyright (c) 2012 dataiku. All rights reserved.
Building the LinkedIn Graph
import oauth2 as oauth
import urlparse
import simplejson
import codecs
CONSUMER_KEY = "your-consumer-key-here"
CONSUMER_SECRET = "your-consumer-secret-here"
OAUTH_TOKEN = "your-oauth-token-here"
OAUTH_TOKEN_SECRET = "your-oauth-token-secret-here"
OUTPUT = "linked.csv"
def linkedin_connections():
# Use your credentials to build the oauth client
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
token = oauth.Token(key=OAUTH_TOKEN, secret=OAUTH_TOKEN_SECRET)
client = oauth.Client(consumer, token)
# Fetch first degree connections
resp, content = client.request('http://api.linkedin.com/v1/people/~/connections?format=json')
results = simplejson.loads(content)
# File that will store the results
output = codecs.open(OUTPUT, 'w', 'utf-8')
# Loop thru the 1st degree connection and see how they connect to each other
for result in results["values"]:
con = "%s %s" % (result["firstName"].replace(",", " "), result["lastName"].replace(",", " "))
print >>output, "%s,%s" % ("Thomas Cabrol", con)
# This is the trick, use the search API to get related connections
u = "https://api.linkedin.com/v1/people/%s:(relation-to-viewer:(related-connections))?format=json" % result["id"]
resp, content = client.request(u)
rels = simplejson.loads(content)
try:
for rel in rels['relationToViewer']['relatedConnections']['values']:
sec = "%s %s" % (rel["firstName"].replace(",", " "), rel["lastName"].replace(",", " "))
print >>output, "%s,%s" % (con, sec)
except:
pass
if __name__ == '__main__':
linkedin_connections()
I received this document from LinkedIn:
https://developer.linkedin.com/blog/posts/2015/transition-faq
Does this mean the API is now closed?
OAuth 1.0a is still supported by LinkedIn, but it is no longer encouraging new implementations.
You must request your own OAuth 1.0a token/secret values as part of the auth workflow. LinkedIn's application management console no longer automatically generates one for you as a convenience.
Switching to OAuth 2.0 would probably be an easier approach.
Further, please note that the call your library appears to be making to get a user's connections is no longer publicly available via the API as per the announcement made on LinkedIn's developer blog back in February (https://developer.linkedin.com/blog/posts/2015/developer-program-changes). So getting authentication working may not be the only problem you encounter.
I am trying to create generic class in python which will do all the oAuth process and then will allow to retrieve data from any oAuth supporting service (for example Twitter,LinkedIn).
Edited:
I have customer key and secret and access token key and secret,when I try to request any resource request I get the following error:
{"error":"Could not authenticate with OAuth.","request":"\/1\/statuses\/retweeted_by_me.json}'
any idea why?
My Code is:
import httplib
import time
import oauth as oauth
# settings for the local test consumer
SERVER = 'api.twitter.com'
RESOURCE_URL = 'https://api.twitter.com/1/statuses/retweeted_by_me.json'
CONSUMER_KEY = 'MY_CUSTOMER_KEY'
CONSUMER_SECRET = 'MY_CUSTOMER_SECRET'
ACCESS_TOKEN_KEY = 'MY_ACCESS_TOKEN_KEY'
ACCESS_TOKEN_SECRET = 'MY_ACCESS_TOKEN_SECRET'
# example client using httplib with headers
class SimpleOAuthClient(oauth.OAuthClient):
def __init__(self, server):
self.server = server
self.connection = httplib.HTTPSConnection(self.server)
def access_resource(self, oauth_request):
# via post body
# -> some protected resources
self.connection.request(oauth_request.http_method, RESOURCE_URL)
response = self.connection.getresponse()
return response.read()
def run_example2():
print '** OAuth Python Library Example **'
client = SimpleOAuthClient(SERVER, )
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
pause()
# access some protected resources
print '* Access protected resources ...'
pause()
token = oauth.OAuthToken('ACCESS_TOKEN_KEY', 'ACCESS_TOKEN_SECRET')
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url=RESOURCE_URL)
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 pause():
print ''
time.sleep(1)
if __name__ == '__main__':
run_example2()
print 'Done.'
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authenticate'
This is the incorrect URL to use for OAuth. If you look at Twitter's 3-legged OAuth documentation, they state "The GET oauth/authorize endpoint is used instead of /oauth/authenticate". Change the URL to "https://api.twitter.com/oauth/authorize" and try again.
I managed to fix it by changing self.connection.request(oauth_request.http_method, RESOURCE_URL)
to self.connection.request(oauth_request.http_method, oauth_request.to_url())
Notice that will will work only if oauth_request.http_method is GET
I am trying to setup this Twitter authorization without having the user to enter the pin in our screen but I am having trouble getting the correct setup I am always directed to enter the PIN. trying to use and follow this package https://github.com/simplegeo/python-oauth2
Here is my current code
env = Environment(loader = PackageLoader('buzzient','tmpl'))
template = env.get_template('authtwitter.html')
tmpldict = {}
#SETUP TWITTER AUTHORIZATION OBJECT
consumer_key = '######################'
consumer_secret = '##############################'
request_token_url = 'http://twitter.com/oauth/request_token'
access_token_url = 'http://twitter.com/oauth/access_token'
authorize_url = 'http://twitter.com/oauth/authenticate'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
#get request token
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid Response %s." %resp['status'])
request_token = dict(urlparse.parse_qsl(content))
tmpldict['twitauthurl'] = "%s?oauth_token=%s" % ( authorize_url, request_token['oauth_token'] )
qargs=buzzientlib.urlparse_qs(self.request.url,True,False)
t = template.render(tmpldict)
self.response_body = str(t)
The template just includes a link to twitauthurl
Switched packages to Tweepy and followed this example
http://packages.python.org/tweepy/html/auth_tutorial.html