Linkedin API invalid access token (Python) - python

I just want to make a hello world post on LinkedIn.
One method is to use selenium, but i would rather use the API if possible.
Another method is to use the API which is well explained here:
https://www.jcchouinard.com/how-to-post-on-linkedin-api-with-python/
I execute the code, and get an access token from the website.
I then use the access token to get the user info.
From this i can make the post.
However, the issue that i have is that the access token can expire:
{
'serviceErrorCode': 65600,
'message': 'Invalid access token',
'status': 401
}
There is a way to get the new token manually here:
https://pypi.org/project/python3-linkedin/
with this instruction When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL: "http://localhost:8000/?code=#############################################&state=########################"
My question is this: Is there a way to get a refreshed access token without having to do this manually ?
(In particular the LinkedIn site indicates that the token is valid for 2 months)

Related

Tweepy: lookup_users() cannot perform write actions, error 261

Hello I am using the Twitter API via Tweepy on Python, since it is a read function, I don't understand why I get the following message:
[{'message': 'Application cannot perform write actions. Contact Twitter Platform Operations through https://help.twitter.com/forms/platform.', 'code': 261}]
When I checked my developer portal I found the following message:
This App has violated Twitter Rules and policies. As a result, certain functions will be limited. An email has been sent to ******#gmail.com with details. For assistance, submit a support ticket.
Which is funny since I have only used the API with my own credentials/user for:
public_tweets = api.user_timeline()
lookup_users = api.lookup_users(user_ids=[user_id])
Additional info:
I gave read, write, post permissions to my app
Why cannot I perform writing actions if this is a read function?
Is there any way I can manage this issue with my app? Twitter is not responding to my appeal
This error code seems to indicate an issue with the app permissions, unspecific to the endpoint:
Code 261 - App cannot perform write actions.
The App that you are using with the API does not have the proper permission level set for its access token and access token secret. Please navigate to the 'Keys and tokens' tab on the Twitter Apps dashboard and check the permission levels assigned to your access token and access token secret. If it is set to anything other than 'Read, write and Direct Messages,' then you are going to have to adjust the settings under the 'Permission' tab and regenerate your access token and access token secret to apply the new settings.
https://developer.twitter.com/en/support/twitter-api/error-troubleshooting
Beyond submitting a support ticket and waiting for a response, I don't think there's much else you can do in terms of the restriction itself.

Accessing sharepoint list with token unclear

I only want to pull data from a list called dataacq within a group (or site?) called prod within the domain (or root site?) tenant.sharepoint.com (or tenant-my.sharepoint.com ?) and put it into a DataFrame.
I have an issue with the token gotten through app.acquire_token_silent.
Microsoft documentation is not comprehensible because it's too heavy and has little workable cookbooks/working examples (as can be seen by my numerous question marks). Also it seems they want to centralize all their APIs into graph.microsoft.com, yet there is no warning that tenant.sharepoint.com/sites/prod/_api/ is going to be discontinued.
I have gotten the following permissions from the azure portal for my app.
I don't believe I need all of them, but I am not sure. I just want to read a list. So is only Microsoft Graph > Sites.read.All necessary? Or is it Sharepoint > Allsites.Read ?
I know I both have an "app only" permission and a "signed in user" permission.
I did download the "quickstart" examples and I did read https://msal-python.readthedocs.io/en/latest/ . Although a token was successfully pulled using app.acquire_token_silent, using the returned token always throws some error whatever scope ('https://microsoft.sharepoint-df.com/.default' or 'https://graph.microsoft.com/.default') or API domain (graph.microsoft.com or tenant.sharepoint.com) I am using into a request:
{'error_description':
"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}
{'error': {'code': 'AccessDenied',
'message': 'Either scp or roles claim need to be present in the token.',
'innerError': {'date': '2021-02-19T08:05:16',
'request-id': '01efc071-18e6-4006-8780-f771419ebe3e',
'client-request-id': '01efc071-18e6-4006-8780-f771419ebe3e'}}}
On the other hand, there is an API developer testing portal. When I am copying the token given in this portal into my python code, both scope/API domains work.
This is e.g. an example that works with copying & pasting the token from the portal, but not working with the token issued by the app.acquire_token_silent method:
r = requests.get( # Use token to call downstream service
fr'https://graph.microsoft.com/v1.0/sites/root:/sites/prod:/lists/{list_id}/items?expand=fields(select=Created))',
headers={'Authorization': 'Bearer ' + result['access_token'],},)
So the issue is with this app.acquire_token_silent method or the configuration file. But the returned response seems alright:
{'token_type': 'Bearer',
'expires_in': 3599,
'ext_expires_in': 3599,
'access_token': '...'}
What am I missing?
According to the code r = requests.get..... you provided in your description, it seems you use the microsoft graph api to implement it. If you use this api, you should use https://graph.microsoft.com/.default as scope to get the access token. And you can copy the access token to this page, decode the token and check if the permissions are included in it.
And according to the screenshot of "API permissions" tab of your registered app, please also do grant admin consent operation for the permission Sites.Read.All although it shows not required admin consent.
================================Update===============================
It seems the method acquire_token_silent() acquire the access token by client credential flow. So we should add the "Application" type permission but not "Delegated" permission in registered app.

How can I get oauth_access_token for facebook-sdk

I want to code that post facebook. So I decided to use python-sdk (https://github.com/pythonforfacebook/facebook-sdk).
Then I hit a problem.
graph = facebook.GraphAPI(oauth_access_token)
How can I get this "oauth_access_token"?
You need to use an authorization flow. Access tokens are the keys used after getting proper authorization.
An access token is an opaque string that identifies a user, app, or
page and can be used by the app to make graph API calls. Access tokens
are obtained via a number of methods, each of which are covered later
in this document. The token includes information about when the token
will expire and which app generated the token. Because of privacy
checks, the majority of API calls on Facebook need to include an
access token.
There are various ways to obtain an access token all explained in https://developers.facebook.com/docs/facebook-login/access-tokens/
For testing, one must create an app at https://developers.facebook.com/apps and can be issued an access token at https://developers.facebook.com/tools/access_token
Here is a way to get the user access token :
instance = UserSocialAuth.objects.get(user=request.user, provider='facebook')
token = instance.tokens
graph = facebook.GraphAPI(token['access_token'])
Maybe you've already figured this out, just in case somebody else is looking for it

Facebook: How to get/update user access token using python?

Currently am using Graph Explorer to get a short-lived user access token and than converting it to a extended token(60 days) by a call to facepy get_extended_access_token method.
Now. consider the scenario where my user access token becomes invalid because of either user logging out or the token expires itself. So, in both the cases I need to get a new user access token because get_extended_access_token requires access_token so that it can extend it.
So, my question is how to retrieve this token using python? Is there any particular url which I can send a request and it will return a new/updated token in resonse.
Update:
So, after following this post and making a request to
https://graph.facebook.com/oauth/access_token?client_id=xxxx&client_secret=yyyy&grant_type=client_credentials
I got this token which I believe is an app access token
access_token=123456789|12abcdef234 #changed from original
But what I need is an user access token through which I can read my mailbox.
If the access token has expired or been invalidated you need to go back through the Auth Dialog, i.e. a user must manually re-grant access to your application. Retrieving it programmatically defeats the whole purpose of token invalidation/expiry.
Once you get this token, you can then use get_extended_access_token to get the long lived one
App tokens can be used to publish a post on the user's behalf.

GData and OAuth in Python: Unable to convert request token to access token

I am trying to implement a button on a web-based dashboard that allows a user to export the current data to a Google Spreadsheet using OAuth and GData API. Currently, I can get the user to a login/grant access page, but if I add the line to convert the request token to an access token, I receive:
"RequestError: Unable to upgrade OAuth request token to access token: 400, parameter_absent
oauth_parameters_absent:oauth_token"
I am following the instructions for OAuth 2 on this page:
https://developers.google.com/gdata/docs/auth/oauth
and have read both PyDocs for the Google APIs and found no details on this issue:
http://gdata-python-client.googlecode.com/hg/pydocs/gdata.docs.client.html#DocsClient
(Won't let me post a this hyperlink but other Pydoc is same URL but replace the piece after pydocs/ with gdata.gauth.html#ClientLoginToken)
This is the code that works:
def createDocsClient(self, oauth_callback_url):
docsClient = gdata.docs.client.DocsClient(source='RiskOps-QualityDashboard')
request_token = docsClient.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
domain = None
auth_url = request_token.generate_authorization_url(google_apps_domain=domain)
self.redirect(str(auth_url))
request_token = gdata.gauth.AuthorizeRequestToken(request_token, self.request.uri
With the above code, I get to a grant access page and if you click the grant access page, you get a 404 error because it doesn't know where to go after (as expected), but the page has the proper URL displayed listing an oauth_verifier and oauth_token. The "AuthorizeRequestToken" line is supposed to use that URL to authorize the token so up to this line, everything seems to work.
When I add the following line right after the code above, I get the "RequestError" I wrote about:
access_token = docsClient.GetAccessToken(request_token)
I've tried different combinations of nesting the calls within each other, using the AeSave and AeLoad (as the instructions mention might be needed but I'm not sure if my case calls for it) and many other random and unsuccessful ideas and nothing is really giving me a good idea of what I'm missing or doing wrong.
Would really appreciate and help or any ideas anyone has.(If you can't tell, I'm fairly inexperienced when it comes to real-world code (as opposed to academic code). Thanks so much.

Categories

Resources