I wanna access gmail use python and oauth2.0,so I download the oauth2.py from "http://google-mail-oauth2-tools.googlecode.com/svn/trunk/python/oauth2.py". And this is my demo:
import oauth2
import imaplib
import email
from oauth2client.client import OAuth2WebServerFlow
from launchpadlib.credentials import access_token_page
email = 'karlvorndoenitz#gmail.com'
client_id = 'client_id'
client_secret = 'client_secret'
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://mail.google.com/'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
authorization_code = raw_input("Please input the code:").strip()
response = oauth2.AuthorizeTokens(client_id, client_secret, authorization_code)
access_token = response['access_token']
auth_string = oauth2.GenerateOAuth2String(email,access_token,base64_encode=True)
print auth_string
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
imap_conn.select('INBOX')
But the demo has some bugs,I don't know how to debug it.The information from console:
16:58.52 > KOMN1 AUTHENTICATE XOAUTH2
16:58.79 < +
16:58.79 write literal size 204
16:59.27 < + eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
16:59.27 write literal size 204
16:59.27 < KOMN1 NO Invalid SASL argument. d10if1169757igr.56
16:59.27 NO response: Invalid SASL argument. d10if1169757igr.56
Traceback (most recent call last):
File "/home/karl/workspace/Gmail/download_gmail/download_gmail_api.py", line 33, in <module>
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
File "/usr/lib/python2.7/imaplib.py", line 351, in authenticate
raise self.error(dat[-1])
imaplib.error: Invalid SASL argument. d10if1169757igr.56
I need help.
The auth_string should not be base64encoded. I believe the IMAP4.authenticate encodes it for you. It worked for me anyways.
For example:
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)
Related
I am trying to configure and use OAuth to authenticate and request token using Python. I have generated jira private key.
import requests
from oauthlib.oauth1 import SIGNATURE_RSA,SIGNATURE_HMAC
from requests_oauthlib import OAuth1Session
from jira.client import JIRA
import time
def read(file_path):
with open(file_path) as f:
return f.read()
CONSUMER_KEY = "OauthKey"
RSA_KEY = read("jira_privatekey.pem")
JIRA_SERVER = "http://rhtstngjira012:8080"
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"
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)
But while requesting tokens, I am getting the following error -
Traceback (most recent call last):
File "Access_Tokens_JIRA.py", line 23, in <module>
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 287, in fetch_request_token
token = self._fetch_token(url, **request_kwargs)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 369, in _fetch_token
raise TokenRequestDenied(error % (r.status_code, r.text), r)
requests_oauthlib.oauth1_session.TokenRequestDenied: Token request failed with code 401, response was 'oauth_problem=signature_invalid&oauth_signature=ABC&oauth_signature_base_string=POST%26http%253A%252F%252Frhtstngjira012%253A8080%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_consumer_key%253DOauthKey%2526oauth_nonce%123%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1630512420%2526oauth_version%253D1.0&oauth_signature_method=RSA-SHA1'
I have installed all latest libraries and have generated keys too. Could you please advise what I can change to request tokens from JIRA?
You should create API token and encode to base64 the whole String email:your-api-token.
You have to create API token for your user as described here: https://confluence.atlassian.com/cloud/api-tokens-938839638.html.
I have been using Google's Picasa API successfully from last 6 months or so.
Today I have started getting an error
raise GooglePhotosException(e.args[0])
GooglePhotosException: (403, 'Forbidden', 'Authorization required')
I checked my credentials.
self.gd_client = gdata.photos.service.PhotosService()
self.gd_client.email = EmailOfTheUploadingPictureAccount
self.gd_client.password = PasswordOfTheAccount
self.gd_client.source = 'destipak' #Not sure about that
self.feed_url = "/data/feed/api/user/"
self.entry_url = "/data/entry/api/user/"
self.gd_client.ProgrammaticLogin()
Everything was working well since yesterday. Anyone has any clues?
EDIT
Example given on Picasa for python is also not working.
URL
#!/usr/bin/python2.5
import gdata.photos.service
import gdata.media
import gdata.geo
gd_client = gdata.photos.service.PhotosService()
gd_client.email = '=change=' # Set your Picasaweb e-mail address...
gd_client.password = '=change=' # ... and password
gd_client.source = 'api-sample-google-com'
gd_client.ProgrammaticLogin()
albums = gd_client.GetUserFeed()
for album in albums.entry:
print 'Album: %s (%s)' % (album.title.text, album.numphotos.text)
photos = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s?kind=photo' % (album.gphoto_id.text))
for photo in photos.entry:
print ' Photo:', photo.title.text
tags = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=tag' % (album.gphoto_id.text, photo.gphoto_id.text))
for tag in tags.entry:
print ' Tag:', tag.title.text
comments = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=comment' % (album.gphoto_id.text, photo.gphoto_id.text))
for comment in comments.entry:
print ' Comment:', comment.content.text
EDIT 2
Full traceback
Traceback (most recent call last):
File "/Users/mac/Picasa_API.py", line 158, in <module>
check_api()
File "/Users/mac/Picasa_API.py", line 140, in check_api
albums = gd_client.GetUserFeed()
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 235, in GetUserFeed
return self.GetFeed(uri, limit=limit)
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 180, in GetFeed
raise GooglePhotosException(e.args[0])
gdata.photos.service.GooglePhotosException: (403, 'Forbidden', 'Authorization required')
Here is the code I use to get OAuth2 authentication working with Picasa. First you need to create a client ID through the Google Developer Console: at https://console.developers.google.com/ and then you must download the client secrets as JSON and pass the filename to OAuth2Login.
The first time you run this code, you will have to authorize the client through your web browser, and paste the code you get there into the application. The credentials are then stored in the file specified by credential_store.
def OAuth2Login(client_secrets, credential_store, email):
scope='https://picasaweb.google.com/data/'
user_agent='myapp'
storage = Storage(credential_store)
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
uri = flow.step1_get_authorize_url()
webbrowser.open(uri)
code = raw_input('Enter the authentication code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
gd_client = gdata.photos.service.PhotosService(source=user_agent,
email=email,
additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})
return gd_client
I ran into this as well. Seems like email/password authentication has been turned off, and we need to switch to OAuth2. See
https://groups.google.com/forum/#!topic/Google-Picasa-Data-API/4meiAJ40l3E
There are my codes:
import pprint
import httplib2
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
SCOPES = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.write']
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_ID = "my client id"
CLIENT_SECRET = "my client secret"
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPES,
redirect_uri=REDIRECT_URI)
auth_uri = flow.step1_get_authorize_url()
print 'Please paste this URL in your browser to authenticate this program.'
print auth_uri
code = raw_input('Enter the code it gives you here: ')
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('plusDomains', 'v1', http=http)
user_id = 'me'
print('Insert activity')
result = service.activities().insert(
userId = user_id,
body = {
'object' : {
'originalContent' : 'Happy Monday! #caseofthemondays'
},
'access' : {
'items' : [{
'type' : 'domain'
}],
'domainRestricted': True
}
}).execute()
print('result = %s' % pprint.pformat(result))
and there are my error:
Traceback (most recent call last):
File "/home/karl/workspace/googleplus/google_plus/google_plus_pic.py", line 44, in <module>
'domainRestricted': False
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 128, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 680, in execute
raise HttpError(resp, content, uri=self.uri)
apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json returned "Forbidden">
I have read a lot of information,but I don't know how to solve the problem.
Where is the bug?
To use the Google+ Domains API, you need to make sure that the Domain for the user you are acting on behalf of has been set up with the right permissions for your app. These instructions are under the "Delegate domain-wide authority to your service account" section of Step 1 of the quick-start guide.
Specifically, you need to associate your app's Client ID with the scopes your app will use in the control panel for the domain. The domain administrator is the only person who can do this--so if you are working with another domain, be sure you get in contact with that person. Also, the scopes listed in the control panel must match EXACTLY with the scopes you request in your app.
I tried so many methods, but none seem to work. Help me make a connection with linkedin using python. I have all the tokens. I have python 2.7.5. Please post a sample of basic code that establishes a connection and gets a user's name.
Below, I have done character for character like the example said, but it doesn't work.
https://github.com/ozgur/python-linkedin <---This is where I got the api and I copied it exactly. See below:
CONSUMER_KEY = '9puxXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_token
USER_SECRET = 'ca103e23XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_secret
from linkedin import linkedin
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
# Use the app....
application.get_profile()
I get this error:
Traceback (most recent call last):
File "C:/Documents and Settings/visolank/Desktop/Python/programs/linkedinapi.py", line 8, in <module>
from linkedin import linkedin
File "C:/Documents and Settings/visolank/Desktop/Python/programs\linkedin\linkedin.py", line 2, in <module>
from requests_oauthlib import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\__init__.py", line 1, in <module>
from .core import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\core.py", line 4, in <module>
from oauthlib.oauth1 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\__init__.py", line 12, in <module>
from .rfc5849 import Client
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\rfc5849\__init__.py", line 26, in <module>
from oauthlib.common import Request, urlencode, generate_nonce
ImportError: No module named oauthlib.common
Got it. For future reference you need to download the oauthlib from here https://github.com/idan/oauthlib
here is the full functional code:
CONSUMER_KEY = '9pux1XcwXXXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb' # This is oauth_token
USER_SECRET = 'ca103e23-XXXXXXXXXXXXXXXXXXXXXXXX7bba512625e' # This is oauth_secret
RETURN_URL = 'http://localhost:8000'
from linkedin import linkedin
from oauthlib import *
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
# Use the app....
g = application.get_profile()
print g
You can get USER_TOKEN & USER_SECRET in such way (if you have CONSUMER_KEY & CONSUMER_SECRET):
import oauth2 as oauth
import urllib
consumer_key = '' #from Linkedin site
consumer_secret = '' #from Linkedin site
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200' :
raise Exception('Invalid response %s.' % resp['status'])
content_utf8 = str(content,'utf-8')
request_token = dict(urllib.parse.parse_qsl(content_utf8))
authorize_url = request_token['xoauth_request_auth_url']
print('Go to the following link in your browser:', "\n")
print(authorize_url + '?oauth_token=' + request_token['oauth_token'])
accepted='n'
while accepted.lower() == 'n' :
accepted = input('Have you authorized me? (y/n)')
oauth_verifier = input('What is the PIN?')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
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')
content8 = str(content,'utf-8')
access_token = dict(urllib.parse.parse_qsl(content8))
print('Access Token:', "\n")
print('- oauth_token = ' + access_token['oauth_token']+'\n')
print('- oauth_token_secret = ' + access_token['oauth_token_secret'])
print('You may now access protected resources using the access tokens above.')
I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.