Python - oauth2 - linkedin API - python

I am trying to follow some companies registered on LinkedIn through python code and as per LinkedIn API documentation I need to use oauth2 - POST method to follow a company.
My queries are below:
How to specify a particular company name via python code to follow a company?
Can someone advise the python code for this?
My code is below:
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "POST"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
def linkedinreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
req.to_postdata()
def fetchsamples():
url = "https://api.linkedin.com/v1/people/~/following/companies"
parameters = []
response = linkedinreq(url, "POST", parameters)
fetchsamples()

The python modules python-linkedin and python-linkedin-v2 are outdated. Thus, I suggest you to use the requests_oauthlib module instead.
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# In case the `redirect_url` does not implement https
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Credentials you get from registering a new application
client_id = '<the client id you get from linkedin>'
client_secret = '<the client secret you get from linkedin>'
redirect_url = '<authorized redirect URL from LinkedIn config>'
# OAuth endpoints given in the LinkedIn API documentation (check for updates)
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn config)
linkedin = OAuth2Session(client_id, redirect_uri=redirect_url)
linkedin = linkedin_compliance_fix(linkedin)
# Redirect user to LinkedIn for authorization
authorization_url, state = linkedin.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')
# Fetch the access token
linkedin.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
# Fetch a protected resource, i.e. user profile
r = linkedin.get('https://api.linkedin.com/v1/people/~')
print(r.content)

Instead of reinventing the wheel, use python-linkedin wrapper.
Example code to search for the companies:
from linkedin import linkedin
CONSUMER_KEY = 'your key'
CONSUMER_SECRET = 'your secret'
USER_TOKEN = 'your token'
USER_SECRET = 'your user secret'
RETURN_URL = ''
# 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)
print application.search_company(selectors=[{'companies': ['name', 'universal-name', 'website-url']}],
params={'keywords': 'apple microsoft'})
To follow the company, use follow_company() method, see more information and examples here:
COMPANY_ID = 1035 # this you would get from the `search_company()`
application.follow_company(COMPANY_ID)

Related

Verify Client ID and Client Secret before using it in Application

We have a use case in which Admin can set Google Or Microsoft's Apps Client Id and Secrets that can later be used for all users who sign up with this Admin's link, Is there a way to verify these fields before saving/using them?
like for Microsoft,How do I verify this info that admin is providing? Is there any API call to verify it?
Update:
I am able to do this for G suite, what I did was:
1- Create a request to get token from client id and secret, (with wrong code).
2- In response, google returns 'invalid_client' in case the credentials are wrong and 'invalid_grant' in case the credentials are correct. (because Code is wrong too.)
try:
discovery_url = settings.GOOGLE_DISCOVERY_URL
callback_url = settings.BASE_URL + "/accounts/invite/google/signup/callback/"
client = WebApplicationClient(client_id)
identity_provider_config = requests.get(
discovery_url,
).json()
token_endpoint = identity_provider_config["token_endpoint"]
token_url, headers, body = client.prepare_token_request(
token_endpoint, redirect_url=callback_url, code='**code'**
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(client_id, client_secret),
).json()
# Parse the tokens!
client.parse_request_body_response(json.dumps(token_response))
except Exception as error:
json_object = json.loads(error.json)
pairs = json_object.items()
if list(pairs)[0][1] == 'invalid_grant':
return "Your credentials are correct"
if list(pairs)[0][1] == 'invalid_client':
return "Your credentials are NOT correct"
FOR MICROSOFT:
For microsoft, additional tenant id is required in order to do this:
We did this in following way:
def validate_azure_credentials(client_id, client_secret, tenant_id):
"""
validate client id and secret from microsoft and google
"""
try:
app = msal.ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=f"https://login.microsoftonline.com/{tenant_id}",
)
# call for default scope in order to verify client id and secret.
scopes = ["https://vault.azure.net/.default"]
token = app.acquire_token_for_client(scopes=scopes)
if token.get("access_token") is None:
return IdpResponseMessages.INVALID_CREDENTIALS
return IdpResponseMessages.VALID_CREDENTIALS
except Exception as error:
logger.debug(f"Exception {error}")
return str(error)

How to use 3-legged OAuth in Tweepy with Twitter API v2 to read protected Tweets?

I am trying to access protected Tweets from Twitter handles using Tweepy and Twitter API v2. To do this I know I have to use 3-legged OAuth. I have done it and successfully generated an access token and access token secret. But with those access keys I am not able to see the protected Tweets of my own protected account when I am authorizing with the same account.
Does anyone know what I am doing wrong here?
This is a login.py file with the authorization function
#!/usr/bin/env python
import tweepy
def authrize():
CONSUMER_KEY = "XXXXXXXXXXXxx"
CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"
BEARER_TOKEN = "XXXXXXXXXXXXXXXX"
auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")
print(auth.get_authorization_url())
verifier = input("Input PIN: ")
ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)
print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
and my tweepy code app.py is as follows
import tweepy
import login
def get_client(CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET):
client = tweepy.Client(bearer_token=BEARER_TOKEN,
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET, wait_on_rate_limit=True)
return client
def get_user_id(username):
user = client.get_user(username=username)
return user.data.id
def pagination(user_id):
responses = tweepy.Paginator(client.get_users_tweets, user_id,
exclude='replies,retweets',
max_results=100,
expansions='referenced_tweets.id',
tweet_fields=['created_at', 'public_metrics', 'entities'])
return responses
def get_original_tweets(user_id):
tweet_list = []
responses = pagination(user_id)
for response in responses:
if response.data ==None:
continue
else:
for tweets in response.data:
tweet_list.append([tweets.text,
tweets['public_metrics']['like_count'],
tweets['public_metrics']['retweet_count'],
tweets['created_at'].date()])
return tweet_list
def user_details(username):
user = {}
user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
user_metrics = user_response.data['public_metrics']
user['description'] = user_response.data['description']
user['followers'] = user_metrics['followers_count']
user['following'] = user_metrics['following_count']
return user
keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))
By default, Client.get_users_tweets uses your bearer token rather than OAuth 1.0a User Context to authenticate. You need to set the user_auth parameter to True.

Twitter API OAuth cannot find 'authorization_url'

I'm writing a code that uses Twitter API to get users' statuses, number of followers etc. I need to write a script that opens browser and asks users to sign in and let me get the authentication from them.
from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
client_key = "keykeykeykey"
client_secret = "keykeykeykeykey"
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1Session(client_key, client_secret=client_secret)
fetch_response = oauth.fetch_request_token(request_token_url)
#print(fetch_response)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth = OAuth1(client_key, client_secret=client_secret)
r = requests.post(url=request_token_url, auth=oauth)
#print(r.content)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
base_authorization_url = 'https://api.twitter.com/oauth/authorize'
authorization_url = oauth.authorization_url(base_authorization_url)
print 'Please go here and authorize,', authorization_url
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
#print(oauth_response)
verifier = oauth_response.get('oauth_verifier')
authorize_url = base_authorization_url + '?oauth_token='
authorize_url = authorize_url + resource_owner_key
print 'Please go here and authorize,', authorize_url
verifier = raw_input('Please input the verifier')
I have found this kind of example from internet but it gives an error like :
AttributeError: 'OAuth1' object has no attribute 'authorization_url'
I have checked the session info and actually there is authorization_url here:
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py
It looks like you use the oauth variable as an OauthSession object and a Oauth1 object.
oauth = OAuth1Session(client_key, client_secret=client_secret)
oauth = OAuth1(client_key, client_secret=client_secret)
It should work if you use it as a session object

Creating a DfpClient with a Service Account in Python

I use the google DFP api to collect some statistics on ads clicked on our website. The
code is written in Python. Currently, I am trying to upgrade the code to use oAuth 2.
Since, the code runs automatically everyday without any user involvement, I created a
service account under my google project and added the account to the DoubleClick for
Publishers network of our company. Based on the sample codes on the web, I wrote this:
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build
from googleads.dfp import DfpClient
GOOGLE_DFP_SCOPE="https://www.googleapis.com/auth/dfp"
API_VERSION="v201411"
KEY_FILE="*******.p12"
ACCT_EMAIL="************************#developer.gserviceaccount.com"
NETWORK_CODE="**********"
with open(KEY_FILE) as config_file:
my_private_key = config_file.read()
credentials = SignedJwtAssertionCredentials(service_account_name=ACCT_EMAIL, private_key=my_private_key,scope=GOOGLE_DFP_SCOPE)
http = httplib2.Http()
http_auth = credentials.authorize(http)
dfp_client = build(serviceName='dfp',version=API_VERSION,http=http_auth)
This code does not seem to be correct, because the network_code has not been passed
anywhere in the code. In addition, it fails with the following message:
apiclient.errors.UnknownApiNameOrVersion: name: dfp version: v201411.
Also, the line below:
dfp_client = DfpClient.LoadFromStorage()
does not work for my case, because, this is based on googleads.yaml which seems
to be formatted only for web-app accounts with client secret, not P12 private key.
Any advice? Thanks.
Apiclient.discovery uses a default route to check the services.
But I did not find a service for DoubleClick for publishers.
I use this code to use API with Oauth2. Using Flask
import json
import requests
import flask
from googleads import dfp
from googleads import oauth2
app = flask.Flask(__name__)
CLIENT_ID = ''
CLIENT_SECRET = '' # Read from a file or environmental variable in a real app
SCOPE = 'https://www.googleapis.com/auth/dfp'
REDIRECT_URI = ''
APPLICATION_NAME = 'DFP API SERVICE'
NETWORK_CODE = ''
#app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback'))
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauth2callback'))
else:
try:
refresh_token = credentials['refresh_token']
oauth2_client = oauth2.GoogleRefreshTokenClient(CLIENT_ID, CLIENT_SECRET, refresh_token)
dfp_client = dfp.DfpClient(oauth2_client, APPLICATION_NAME, NETWORK_CODE)
user_service = dfp_client.GetService('UserService', version='v201508')
user = user_service.getCurrentUser()
return flask.render_template('index.html', name=user['name'])
except:
flask.session.pop('credentials', None)
return flask.redirect(flask.url_for('oauth2callback'))
#app.route('/oauth2callback')
def oauth2callback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/auth?response_type=code'
'&access_type=offline&client_id={}&redirect_uri={}&scope={}&').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'}
r = requests.post('https://www.googleapis.com/oauth2/v3/token', data=data)
flask.session['credentials'] = r.text
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run()
I hope this help you
You are correct. You have to pass the network code when you create a dfp client. And version is not necessary. Try the following code to create the client in python.
import os
from googleads import oauth2
from googleads import dfp
def get_dfp_client():
application_name = "Your application name" # from google developer console. eg: Web Client
network_code = ********
private_key_password = 'notasecret'
key_file = os.path.join('path/to/p12file')
service_account_email = '****#***.iam.gserviceaccount.com'
# create oath2 client(google login)
oauth2_client = oauth2.GoogleServiceAccountClient(
oauth2.GetAPIScope('dfp'), service_account_email, key_file)
dfp_client = dfp.DfpClient(oauth2_client, application_name, network_code)
return dfp_client
client = get_dfp_client()
Reference
Please comment if you need more clarification.
Update
googleads renamed module dfp to ad_manager, docs here – Gocht

Cannot retrieve authenticated data from Twitter using access_token

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

Categories

Resources