Where to get USER_TOKEN & USER_SECRET for LinkedIn Scraping - python

I am trying just to access my own LinkedIn profile data.
Steps followed:
Setup a new application
Get CLIENT_ID and CLIENT_SECRET
But, where to get the USER_TOKEN, USER_SECRET as mentioned here "You can simply use the 4 credentials that are provided to you in your LinkedIn application as part of an OAuth 1.0a flow and immediately access your data."? I've tried without it, and it doesn't work.
The code is given in under the Developer Authentication headline here.

The OAuth 1.0a flow has been deprecated by LinkedIn (https://engineering.linkedin.com/blog/2018/12/developer-program-updates), so there is no way to get a user token and secret without going through the OAuth 2 flow described here:
https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/compliance/context

Related

Calling onedrive methods with graph api

I've purchased MS Office and they give me a space on onedrive.
Now I want to operate with that via ms graph API in my python console application (I used python onedrivesdk before but now it is said that it is deprecated).
I have registered an application and can see it via Azure AD on portal.azure.com.
Currently I'm trying to interact with my onedrive like this:
tenant_id = 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'
authority = f'https://login.microsoftonline.com/{tenant_id}'
scope = 'https://graph.microsoft.com/.default'
app = msal.ConfidentialClientApplication(self.client_id, authority=authority, client_credential=self.client_secret)
result = app.acquire_token_silent(["https://graph.microsoft.com/.default"], account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
authToken = result['access_token']
#### Make a call to the graph API
graphResponse = requests.get('https://graph.microsoft.com/beta/me/drive',headers={'Authorization':f'Bearer {authToken}'})
if graphResponse.status_code != 200:
print('Error code: ', graphResponse.status_code)
print(graphResponse.text)
I successfully get an access token, but when I try to call /me/drive
I get status_code = 400 with
Current authenticated context is not valid for this request. This
occurs when a request is made to an endpoint that requires user
sign-in. For example, /me requires a signed-in user. Acquire a token
on behalf of a user to make requests to these endpoints. Use the
OAuth 2.0 authorization code flow for mobile and native apps and the
OAuth 2.0 implicit flow for single-page web apps
I've add permissions for the application on the portal via "API permission -> Add permission", but I'm unable to grant admin consent (In another ms account I have full fledged azure subscription where I'm an admin) because I'm not an admin. But who is admin of this account my MS office assigned to?
According to the code you provided, you use OAuth 2.0 client credentials flow to complete Azure AD auth and get access token. The access token required by service principal. We cannot use the access token to call /me/drive endpoint. We just can use the access token to call /users/<UserObjectIdOrUserPrincipalName}>/drive endpoint. For more details, please refer to the document
So if you want to call /me/drive endpoint, I suggest you use the OAuth 2.0 authorization code flow. Regarding how to implement it in your application, please refer to the sample.

How do you refresh an authentication token with Authlib and GSpread?

I'm using gspread in a python app to access some backend Google Sheets that act as a database for the application. The user is required to log into the app using an in app browser and an authlib OAuth2 session is created using the token returned in the url via this method. The initial log in and access works fine, but when the token times out after an hour I access the sheets anymore and the app breaks.
I can't work out how to refresh the token using authlib, the reason we picked the library is because it integrated with gspread and the it was supposed to autorefresh auth tokens for you. The code that I use for login is below but after an hour the gspread function open_by_key() fails because of the authentication problem.
I have tried recreating the gspread client, but that just uses the same token. I feel like there should be a way to refresh the token to extend its life for another hour but I can't find how to do that with authlib.
creds = OAuth2Session(clientId, clientSecret, scope=scope, redirect_uri=redirectUrl)
authUrl, state = creds.create_authorization_url('https://accounts.google.com/o/oauth2/v2/auth', response_type='token')
Load the authURL in the browser and get user to log in. Browser returns the authentication response as urlString
creds.fetch_access_token(authorization_response=urlString)
gc = gspread.Client(None, creds)
ss = gc.open_by_key(sheetKey)
todaysSheetName = datetime.datetime.now().strftime('%d-%m-%Y')
wks = ss.worksheet(todaysSheetName)
authUrl, state = creds.create_authorization_url('https://accounts.google.com/o/oauth2/v2/auth', response_type='token')
According to this code you are using, response_type=token is an implicit grant type flow. I guess there won't be a refresh_token in token with implicit flow. Here are my suggestions:
try change it to authorization code flow
use a database to save tokens
if the token is expired, use your previously saved token's refresh_token to exchange a new token.
The refresh_token method is simple:
refresh_token(url=None, refresh_token=None, body='', auth=None, headers=None, **kwargs)
Using your code, it should be:
refresh_token = your_previous_token.refresh_token
new_token = creds.refresh_token('https://accounts.google.com/...', refresh_token=refresh_token)
The problem is that there is no documentation on this part. But according to the API, it would be used like this. If it is not working, you can report it to Authlib issue tracker.

Buffer API authentication with Python

I'm trying to authorise the API for Buffer (the social media scheduling app). I'm following the instructions here https://buffer.com/developers/api/oauth
The first step of the authorisation, redirects the user to an authorisation page using a request of the type:
GET https://bufferapp.com/oauth2/authorize?
client_id=...&
redirect_uri=...&
response_type=code
Once authorise the page redirects to the redirect_uri with the authorisation code as a query parameter:
http://example.com/back?code=1/mWot20jTwojsd00jFlaaR45
That code is then to be used in a POST request to obtain an access token:
POST https://api.bufferapp.com/1/oauth2/token.json
POST Data
client_id=...&
client_secret=...&
redirect_uri=...&
code=...&
grant_type=authorization_code
However, the authorisation code has a 30sec valid life.
When I do the authorisation manually and then a POST request with the auth_code I receive like so:
my_data = {
'client_id': my_client_id,
'client_secret': my_client_secret,
'redirect_uri': my_redirect_uri,
'code': auth_code,
'grant_type': 'authorization_code',
}
token = requests.post('https://api.bufferapp.com/1/oauth2/token.json', data=my_data)
I get an "invalid grant" error.
I looked up the error in relation to other APIs (Buffer API doesn't seem to be used that much) and one cause for it might be an expired auth_code. Which wouldn't be surprising given the short shelf life.
What's a good way to automate the authorisation bit to avoid expiration of the auth_code?
Or is it something else I'm doing wrong here?
Many thanks in advance for your help
Buffer is an OAuth 2.0 provider.
You have to use a OAuth 2 Workflow, read about
Requests-OAuthlib: OAuth 2 Workflow
The following sections provide some example code that demonstrates some of the possible OAuth2 flows you can use with requests-oauthlib. We provide four examples: one for each of the grant types defined by the OAuth2 RFC. These grant types (or workflows) are the Authorization Code Grant (or Web Application Flow), the Implicit Grant (or Mobile Application Flow), the Resource Owner Password Credentials Grant (or, more succinctly, the Legacy Application Flow), and the Client Credentials Grant (or Backend Application Flow).

Automating 3-factor authentication through a script for the Lyft Api

I'm trying to use the Lyft rides python API to access Lyft data. Specifically, I'm trying to access the ride estimate endpoint .
from lyft_rides.auth import ClientCredentialGrant
from lyft_rides.session import Session
from lyft_rides.client import LyftRidesClient
auth_flow = ClientCredentialGrant(client_id=MY_ID, client_secret=MY_SECRET, scopes="public")
session = auth_flow.get_session()
client = LyftRidesClient(session)
response = client.get_cost_estimates(start_latitude=start_lat, start_longitude=start_long, end_latitude=end_lat, end_longitude=end_long)
However, the surge rate in the response data is always 0, even during surge hours, and I've diagnosed that it's because I'm not utilizing the 3-legged authentication.
From the lyft developer docs,
3-Legged flow for accessing user-specific endpoints.
To make ride
requests or otherwise access user data, the user must grant you
access. Users who don't have a Lyft account will be prompted to create
a new account if they are directed through the following flow.
From the python docs,
Authorization
If you need access to a Lyft user’s account in order to make requests
on their behalf, you will go through a “3-legged” flow. In this case,
you will need the user to grant access to your application through the
OAuth 2.0 Authorization Code flow. See Lyft API docs.
The Authorization Code flow is a two-step authorization process. The
first step is having the user authorize your app and the second
involves requesting an OAuth 2.0 access token from Lyft. This process
is mandatory if you want to take actions on behalf of a user or access
their information.
from lyft_rides.auth import AuthorizationCodeGrant
auth_flow = AuthorizationCodeGrant(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_PERMISSION_SCOPES,
)
auth_url = auth_flow.get_authorization_url()
Navigate the user to the auth_url where they can grant access to your
application. After, they will be redirected to a redirect_url with the
format REDIRECT_URL?code=UNIQUE_AUTH_CODE. Use this redirect_url to
create a session and start LyftRidesClient.
session = auth_flow.get_session(redirect_url)
client = LyftRidesClient(session)
credentials = session.oauth2credential
Keep credentials information in a secure data store and reuse them to
make API calls on behalf of your user. The SDK will handle the token
refresh for you automatically when it makes API requests with a
LyftRidesClient.
Question
I'm trying to automate the python request within a script. Given that the 3rd leg of the authentication requires manually visiting a url and obtaining a code, is it possible to do this through a script?
[Full Disclosure: I'm one of Lyft's Developer Advocates]
The only way to get that data is by requesting therides.request scope is through the 3-legged OAuth flow (sorry about that). However, you only need to request this external authorization once if you ask for the offline scope as part of the initial authorization. If you have that scope requested initially, you can use refresh_tokens as outlined here and not get prompted for the external URL:
https://developer.lyft.com/docs/authentication#section-step-5-refreshing-the-access-token
If you're only using this script locally I'd recommend going through this authorization once and then building in refresh token logic into your script if your token has expired. Hope that helps!

Django / Python oauth2 for facebook

Any tips on python oauth2 and facebook.
It seems there are little information since Facebook updated to OAuth2.
Is there anyway the existing Twitter library can be used to suite the facebook authentication?
import oauth2 as oauth
# Create your consumer with the proper key/secret.
consumer = oauth.Consumer(key="your-twitter-consumer-key",
secret="your-twitter-consumer-secret")
# Request token URL for Twitter.
request_token_url = "http://twitter.com/oauth/request_token"
# Create our client.
client = oauth.Client(consumer)
# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
print resp
print content
If your looking for readily available Django apps to integrate with your project, check out the authentication packages. Most of them that provide Facebook authentication have been updated to support the OAuth 2 protocol for some time already.
If, on the other hand, you'd like to work with a provider through an OAuth 2 library directly, take a look at python-oauth2--there's a lengthy example of how you can integrate it with Django's authentication immediately in the README.
There is an awesome project called Fandjango and Facepy. Simply, you don't even have to know or even worry about OAuth protocols anymore.
If you want all the user's details or are integrating more of Facebook's graph api, you should have a look at:
https://github.com/tschellenbach/Django-facebook
For a demo of how slick it is:
http://www.fashiolista.com/intro_wide/
Features (Copied from github)
Access the Facebook API, from:
Your website (Using javascript OAuth)
Facebook canvas pages (For building facebook applications)
Mobile (Or any other flow giving you a valid access token)
Django User Registration (Convert Facebook user data into a user model)
Use Facebook data to register a user with your Django app. Facebook connect using the open graph API.
Facebook FQL access
OAuth 2.0 compliant
Includes Open Facebook (stable and tested python client to the graph API)

Categories