Connect to Twitter given already have token? - python

I have looked at all the Python Twitter API wrappers that I could find on Bitbucket, Github and PyPi, but have been unable to find one which allows you to connect to Twitter if you already have the authentication token.
I am aware that I can generate the authentication token using an OAuth token, OAuth token secret, Twitter Token and Twitter Secret; but I would like to skip that processing + not prompt users who already have accounts.
The tweepy library seems popular; but lacks documentation...
Would someone be able to show me a tweet postage which uses Tweepy (or any other Python Twitter library) that uses only the authentication token?
EDIT: I ended up getting to work right with Twython.

You have to store the access token and secret returned by the provider after authentication and use them in the subsequent requests to read or write. I have been using rauth (https://github.com/litl/rauth) and highly recommend it.
EDIT
Assuming you have already have a valid access token and a secret you can create a service object and read or write data using the twitter API (skipping the authentication steps). I have included the necessary steps from the rauth documentation below:
twitter = OAuth1Service(
name='twitter',
consumer_key='YOUR_CONSUMER_KEY',
consumer_secret='YOUR_CONSUMER_SECRET',
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',
header_auth=True)
params = {'include_rts': 1, # Include retweets
'count': 10} # 10 tweets
response = twitter.get('https://api.twitter.com/1/statuses/home_timeline.json',
params=params,
access_token=access_token,
access_token_secret=access_token_secret,
header_auth=True)

Related

How to decode Firebase JWT token in Python

I have added Firebase to allow clients to authenticate directly from the web app client (browser). I am using the firebase-web JS package and it works great. I can see in my browser that I receive a user object with information about the user, including an idToken.
I need to then authenticate this user on my server backend, which is python django. In the Firebase docs I found a how-to for exactly what I am trying to do, which is to verify the id token.
Since they don't have the supported Firebase sdk for python, I need to use a third party solution. I have come to the python-jose package after finding it listed on the jwt.io site. The example looks simple enough:
jwt.decode(token, 'secret', algorithms=['RS256'])
This is my first time using JWT. I don't know what to use for the 'secret'. I tried pasting my id token as token, and the web API key from the Firebase console for secret, but got this error:
jose.exceptions.JWKError: RSA key format is not supported
I also tried the JWT debugger, which seems to be reading most of my id token correctly, but the signature verification is looking for a public and/or a private keys, which like the 'secret' are escaping me.
I am really at a loss for how to find this secret, and how to verify the JWT id token in general. The information on the Firebase docs (third-party section) is:
Finally, ensure that the ID token was signed by the private key
corresponding to the token's kid claim. Grab the public key from
https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com
and use a JWT library to verify the signature. Use the value of
max-age in the Cache-Control header of the response from that endpoint
to know when to refresh the public keys.
I have tried pasting the whole json blob from that googleapis url into the JWT debugger, but still getting an "invalid signature" alert. I don't understand how to use that public key.
Should python-jose work for this approach? If so, what should I use for the secret? If not, can someone point me in the right direction?
Thanks.
I finally found the answer I was looking for in this post: Migrating Python backend from Gitkit to to Firebase-Auth with python-jose for token verification
Since the time of the post there have been updates made to the python-jose package, which gives better support for firebase id tokens. Here is some working code ( jose version 1.3.1 ) on how to use python to decode the firebase id token:
import urllib, json
from jose import jwt
idtoken = "<id token passed to server from firebase auth>"
target_audience = "<firebase app id>"
certificate_url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com'
response = urllib.urlopen(certificate_url)
certs = response.read()
certs = json.loads(certs)
#will throw error if not valid
user = jwt.decode(idtoken, certs, algorithms='RS256', audience=target_audience)
print user

Authorize application to use twitter ads api via OAuth2

I'm using Python's Twython library and want to get access to Twitter Ads API. I've register application and gain app id and app secret key and also get access token. How I can authorize my own application to get access to my own Twitter Ads Campaign? I've authorized via Twython instance, but when I make a request, for example twitter.request('https://ads-api.twitter.com/0/stats/accounts/{0}/campaigns/{1}'.format(ACCOUNT_ID, CAMPAIGN_ID)) I get 401 Error: Unauthorized. Please, help.
Thank you in advance.
The Twitter Ads API only supports OAuth 1.0A at this time. Twython and other libraries support this user-context auth method for Twitter APIs (same method used for statuses/update), or you could use an OAuth lib directly, such as oauth2 -- which has a misleading name, it's actually OAuth 1.0A.
More on this:
https://twitter.com/AdsAPI/status/662626967775264768
https://dev.twitter.com/ads/overview/getting-started
Mini sample of this using Twitter APIs with OAuth 1.0A and oauth2 library is here.

Authentication with the Google Docs List API, Python and OAuth 2

I'm trying to use the Google Docs API with Python+Django and OAuth 2. I've got the OAuth access token, etc. via google-api-python-client, with the code essentially copied from http://code.google.com/p/google-api-python-client/source/browse/samples/django_sample/plus/views.py
Now, I assume I should be using the google gdata API, v 2.0.17. If so, I'm unable to find exactly how to authorize queries made using the gdata client. The docs at http://packages.python.org/gdata/docs/auth.html#upgrading-to-an-access-token (which appear outdated anyway), say to set the auth_token attribute on the client to an instance of gdata.oauth.OAuthToken. If that's the case, what parameters should I pass to OAuthToken?
In short, I'm looking for a brief example on how to authorize queries made using the gdata API, given an OAuth access token.
The OAuth 2.0 sequence is something like the following (given suitably defined application constants for your registered app).
Generate the request token.
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT)
Authorise the request token. For a simple command-line app, you can do something like:
print 'Visit the following URL in your browser to authorise this app:'
print str(token.generate_authorize_url(redirect_url=REDIRECT_URI))
print 'After agreeing to authorise the app, copy the verification code from the browser.'
access_code = raw_input('Please enter the verification code: ')
Get the access token.
token.get_access_token(access_code)
Create a gdata client.
client = gdata.docs.client.DocsClient(source=APP_NAME)
Authorize the client.
client = token.authorize(client)
You can save the access token for later use (and so avoid having to do the manual auth step until the token expires again) by doing:
f = open(tokenfile, 'w')
blob = gdata.gauth.token_to_blob(token)
f.write(blob)
f.close()
The next time you start, you can reuse the saved token by doing:
f = open(tokenfile, 'r')
blob = f.read()
f.close()
if blob:
token = gdata.gauth.token_from_blob(blob)
Then, the only change to the authentication sequence is that you pass this token to OAuth2Token by specifying a refresh_token argument:
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT,
refresh_token=token.refresh_token)
Hope this helps. It took a while to work it out :-).
This is from https://developers.google.com/gdata/docs/auth/overview:
Warning: Most newer Google APIs are not Google Data APIs. The Google Data APIs documentation applies only to the older APIs that are listed in the Google Data APIs directory. For information about a specific new API, see that API's documentation. For information about authorizing requests with a newer API, see Google Accounts Authentication and Authorization.
You should either use OAuth for both authorization and access or OAuth 2.0 for both.
For OAuth 2.0 API are now at https://developers.google.com/gdata/docs/directory.

Getting started with Twitter\OAuth2\Python

I'm attempting to connect to twitter using python, and I'm finding it really frustrating.
Everything I read suggests that I need a consumer key, a consumer secret, an access key and an access secret - for example: Using python OAUTH2 to access OAUTH protected resources
I can get the consumer key and the consumer secret from the twitter settings page for the little test app I created, but what about the other two? After a bit of googling it seems everyone thinks it's so obvious where you get this info from that it's not worth putting up, so I might be having a really dumb moment but could someone please spell it out for idiots like me please?
Edit:
OK to get these details open your app settings in Twitter and click the "My Access Token" link.
I suppose when looking for an Access Token, if you were to click on a link titled "My Access Token" might help. I'd love to attribute my stupidity to the wine, but really I don't know...
Almost all oauth examples on blogs seem to be examples of the authorisation phase of oauth and none focus on how to actually make requests once you have these, as once you understand how it works this part is quite obvious. Getting that initial understanding is quite difficult unfortunately.
If you're just trying access your twitter account from a script or app for yourself you can get the access token (called key in the python oauth library) and secret from dev.twitter.com at the bottom of the settings page for your app under the heading Your access token.
import oauth2 as oauth
import json
CONSUMER_KEY = "your app's consumer key"
CONSUMER_SECRET = "your app's consumer secret"
ACCESS_KEY = "your access token"
ACCESS_SECRET = "your access token secret"
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)
client = oauth.Client(consumer, access_token)
timeline_endpoint = "https://api.twitter.com/1.1/statuses/home_timeline.json"
response, data = client.request(timeline_endpoint)
tweets = json.loads(data)
for tweet in tweets:
print tweet['text']
This example is using the python lib python-oauth2, which is an unfortunately named OAuth library not an OAuth2 library.
If you want to actually let other people authorise their account to be used by your app then you need to implement the redirect dance where you ask twitter for a request token/secret pair and then redirect the user to the twitter authorize page with this request token, they sign in and authorize the token and get redirected back to your application, you then exchange the request token for an access token and secret pair which you can store and use to make requests like above.
The Twitter Three-legged OAuth Example in the Readme at http://github.com/simplegeo/python-oauth2 seems to cover what needs to be done
Personally I use tweepy, it provides a nice python wrapper to Twitter's API

Sending out twitter retweets with Python

I wanted to know if this was possible- I want to use Python to retweet every tweet a person sends out. If yes then how can I implement this?
Unfortunately, python-twitter does not yet support the Twitter Retweet REST call.
You'll have to make that call directly yourself (using direct calls to api._FetchURL) or apply the patch in issue 130 to add support.
You're better off with using tweepy; read the API documentation, there is a handy retweet(id) method for retweeting.
Quick and dirty example:
import tweepy
auth = tweepy.BasicAuthHandler("username", "password")
api = tweepy.API(auth)
for status in api.user_timeline('someuser'):
api.retweet(status.id)
This will retweet the last 20 statuses from someuser. You'll want to do some more coding to prevent it from retweeting those same messages again next time you run the script though.
Edit: Twitter no longer accepts BasicAuth authentication, and you'll have to use the OAuth authentication exchange to get a authorisation token. Changing the example above to use OAuth would detract from the retweet API point I was trying to make, see the Tweepy OAuth tutorial for an extensive tutorial.
It's possible to retweet anything the people you follow tweet.You can also retweet all of the public tweets.
Use this link : https://github.com/joshthecoder/tweepy
you will know how to do it in a very simple way .
Here's the OAuth "Quick and dirty" method, please keep in mind that you will need to have Tweepy installed for this to work.
import tweepy
api_key = 'your_key'
api_secret = 'your_secret_key'
access_token = 'your_token'
access_secret = 'your_secret_token'
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
for status in api.user_timeline('someuser'):
api.retweet(status.id)
The newest version of python-twitter allows you to retweet with the command
api.PostRetweet(tweet_id)
where api is a logged-in api and tweet_id is the id of the tweet you want to retweet.

Categories

Resources