JIRA request token fetch error using Python - python

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.

Related

Gmail API Push Notifications gives Error 403

I am trying to get push notifications regarding all the new inbox messages I receive in my email. I have configured the pubsub client as mentioned in the pubsub doc. Following is the code:
import httplib2
from apiclient import discovery
from oauth2client import client as oauth2client
from lib.common.models.main.users import User
from oauth2client.client import SignedJwtAssertionCredentials,\
AccessTokenRefreshError
PUBSUB_SCOPES = ['https://www.googleapis.com/auth/pubsub']
def create_pubsub_client(http=None):
credentials = oauth2client.GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
credentials = credentials.create_scoped(PUBSUB_SCOPES)
if not http:
http = httplib2.Http()
credentials.authorize(http)
return discovery.build('pubsub', 'v1', http=http)
pubsub = create_pubsub_client()
topic = 'projects/<project-name>/topics/<Topic-name>'
policy = {
'policy': {
'bindings': [{
'role': 'roles/pubsub.publisher',
'members': ['serviceAccount:<my-service-account>'],
}],
}
}
resp = pubsub.projects().topics().setIamPolicy(resource=topic, body=policy).execute()
request = {
'labelIds': ['INBOX'],
'topicName': 'projects/<project-name>/topics/<Topic-name>'
}
f = file('link-to.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'service-account-email',
key,
scope='https://mail.google.com/',
)
user = User.query.filter(User.id == 143).first()
accesskey = user.get_access_key(True)
credentials.access_token = accesskey['key']
service = discovery.build('gmail','v1',credentials=credentials)
service.users().watch(userId='me', body=request).execute()
When I run the above Program, I encounter the following error:
Traceback (most recent call last):
File "/home/kmittal/workspace/engine/workers/newPubSubClient.py", line 82, in
service.users().watch(userId='me', body=request).execute()
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/watch?alt=json returned "Invalid topicName does not match projects/SOME_ANOTHER_PROJECT/topics/*">
As per this other answer, it looks like you can only create a watch for topics that are part of your own project, not another project. The documentation seems to back this up as it implies you must specify myproject (your own project ID):
The topic name can be any name you choose under your project (i.e.
matching projects/myproject/topics/*, where myproject is the Project
ID listed for your project in the Google Developers Console).

Twitter API trends function errors

I'm trying to learn social web mining from this python book entitled Mining the social web, and I'm getting on the first few functions, here's my output:
import twitter
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN_SECRET = ''
OAUTH_TOKEN = ''
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
print twitter_api
WORLD_WOE_ID = 1
US_WOE_ID = 23424977
world_trends = twitter_api.trends.place(_id=WORLD_WOE_ID)
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 245, in call
return self._handle_response(req, uri, arg_data, _timeout)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 276, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 400 for URL: 1.1/trends/place.json using parameters: (id=1&oauth_consumer_key=&oauth_nonce=9996743856969920690&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1406787153&oauth_version=1.0&oauth_signature=NAVC2M%2FtUQRL3xtuWZRqsuP1rCg%3D)
details: {"errors":[{"message":"Bad Authentication data","code":215}]}
What seems to be the problem here, how can I use this function correctly?
You should get access token before accessing the twitter url. Follow this link to get the access token.

how to access gmail use python?

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)

How to use linkedin API with python

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.')

python dropbox api error

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.

Categories