Refresh Access Token Python-Fitbit (Orcasgit) - python

I can't figure out how to refresh my access token using this: https://github.com/orcasgit/python-fitbit
I've been able to get my Access Token, and Refresh Token. I've also been able to pull data from fitbit. But after my Access Token Expires I'm lost. I think I'm supposed to create a FitbitOauth2Client object, and use the refresh_token function to get a new token. Below is the closest I've gotten.
tokenfresh=fitbit.FitbitOauth2Client(client_id=ci,client_secret=consumer_secret,access_token=at,refresh_token=rt)
I've scoured all over for an answer so any help would be much appreciated.

The problem is not your code, FitBit provides a new refresh token when you use an older refresh token to generate an access token. You should keep track of this refresh token in order make you code work.
eg.
def fitbit_data(credentials):
client_id = os.environ.get("FITBIT_CLIENT_ID")
client_secret = os.environ.get("FITBIT_CLIENT_SECRET")
oauth = fitbit.FitbitOauth2Client(client_id=client_id,
client_secret=client_secret,
refresh_token=str(credentials.get('refresh_token')),
access_token=str(credentials.get('access_token')))
token = oauth.refresh_token()
update_refresh_token(token)
app_client = fitbit.Fitbit(client_id=client_id, client_secret=client_secret,
access_token=token.access_token, refresh_token=token.refresh_token)
steps = app_client.time_series(
resource='activities/steps',
period='1d'
)
return steps

Related

Persist Youtube Data API access token in Python desktop app

I have a Python application that accesses Youtube-Data-API v3.
After the program runs for an hour, it throws an error suggesting the access token has expired.
How can I persist the token for a longer period?
There is now way to extend the time for access token. They get expired after an hour. The only way of using a token is to get a new token using refresh_token provided by the api.
First you get offline token by setting access_type to offine while authenticating the user.
{
'response_type': 'code',
'client_id': 'client_id',
'redirect_uri': '...',
'access_type':'offline',
'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}
you will get refresh_token, access_token, id_token along with expiry and some other fields which you can save in you database and fetch later when needed.
Before using the access_token you check if it is valid
creds = google.oauth2.credentials.Credentials(access_token,refresh_token=refresh_token,id_token=id_token,token_uri=token_uri,client_id=client_id,client_secret=client_secret,scopes=scopes,expiry=expirytime)
if creds.valid == False:
// Refresh to get the new token
req =google.auth.transport.requests.Request()
creds.refresh(req)
// Now Save new Credentials from "creds" so that you can use later.
After verifying the access_token you can now query youtube data api requests
youtube = googleapiclient.discovery.build(
"youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()
When you create O-Auth2 credentials, you need to select "Web App" which is what I think you're trying to create. (A website, correct?).
The "Desktop-App" option is for if you want to make a desktop application, not a website.
Desktop applications and web applications handle redirect uris differently, which is what's causing your issue.

Python Uber SDK does not update access token after 30 days based on refresh token

I've created a script for Uber and it worked fine until my access token expired.
So here's this piece of code (almost similar to Uber SDK https://github.com/uber/rides-python-sdk):
session = Session(oauth2credential=OAuth2Credential(
client_id=credential_dict.get('client_id'),
access_token=credential_dict.get('access_token'),
expires_in_seconds=credential_dict.get('expires_in_seconds'),
scopes=credential_dict.get('scopes'),
grant_type=credential_dict.get('grant_type'),
redirect_url=credential_dict.get('redirect_url'),
client_secret=credential_dict.get('client_secret'),
refresh_token=credential_dict.get('refresh_token')))
client = UberRidesClient(session)
With the expired token I can not do anything further, it returns
uber_rides.errors.ClientError: 401: No authentication provided.
Also, I'm confused by "The SDK will handle the token refresh for you automatically when it makes API requests with an UberRidesClient."
How can I get my new access token using refresh token? I can authorize again and it works but is annoying.
You can get new access token if you have valid refresh token by using the token endpoint: https://login.uber.com/oauth/v2/token. For more information check the Uber documentation.
"When the user’s access_token has expired, obtain a new access_token by exchanging the refresh_token that is associated with the access_token using the Token endpoint".

How to apply Spotify API authentication on my current code which uses Spotify Search API?

Earlier I was using Spotify's Search API
without any kind of authentication. But just last week or so, they made their API usage with Authentication only.
So since the past 2-3 days I've not been able to figure how this authorization works for Search API where I as a developer can let users access responses from Search API without having them to login with their Spotify accounts.
Can someone help me with this authorization stuff(The docs from Spotify don't solve my problem :< )
So here's the python code that I was earlier using -
import requests
import json
def Spotify(keyword):
url = "https://api.spotify.com/v1/search?q="+keyword+"&type=track&limit=1"
headers = {
'accept': "application/json",
'access_token':''
}
r = requests.get(url=url,headers=headers).text
jsonwa = json.loads(r)
name = jsonwa["tracks"]["items"][0]["name"]
artists = jsonwa["tracks"]["items"][0]["artists"][0]["name"]
song_preview_url = jsonwa["tracks"]["items"][0]["preview_url"]
image = jsonwa["tracks"]["items"][0]["album"]["images"][1]["url"]
return_this = []
return_this.append(name)
return_this.append(artists)
return_this.append(song_preview_url)
return_this.append(image)
print return_this
return return_this
song = "hello"
Spotify(song)
Per the web authorization docs:
All requests to the Spotify Web API require authorization
You'll need your users to grant permission for your app in order to get an access token. The user must be logged in to gran permission.
Once your app is granted permission by the user, you can use the refresh_token from that point on, and the user shouldn't need to grant permission again unless they revoke permission for example. You'll need to manage the access_token expiration.

Working with the Box.com SDK for Python

I am trying to get started with the Box.com SDK and I have a few questions.
from boxsdk import OAuth2
oauth = OAuth2(
client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
store_tokens=your_store_tokens_callback_method,
)
auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL')
def store_tokens(access_token, refresh_token):
# store the tokens at secure storage (e.g. Keychain)
1)What is the redirect URL and how do I use it? Do I need to have a server running to use this?
2)What sort of code to I need in the store_tokens method?
The redirect URL is only required if you're runng a Web application that needs to respond to user's requests to authenticate. If you're programtically authenticating, you can simply set this as http://localhost. In a scenario where you require the user to manually authenticate, the redirect URL should invoke some function in your web app to store and process the authentication code returned. Do you need a server running? Well, if you want to do something with the authentication code returned, the URL you specify should be under your control and invoke code to do something useful.
Here's an example of what the store_tokens function should look like. It should accept two parameters, access_token and refresh_token. In the example below, the function will commit these to a local store for use when the API needs to re-authenticate:
From here:
"""An example of Box authentication with external store"""
import keyring
from boxsdk import OAuth2
from boxsdk import Client
CLIENT_ID = 'specify your Box client_id here'
CLIENT_SECRET = 'specify your Box client_secret here'
def read_tokens():
"""Reads authorisation tokens from keyring"""
# Use keyring to read the tokens
auth_token = keyring.get_password('Box_Auth', 'mybox#box.com')
refresh_token = keyring.get_password('Box_Refresh', 'mybox#box.com')
return auth_token, refresh_token
def store_tokens(access_token, refresh_token):
"""Callback function when Box SDK refreshes tokens"""
# Use keyring to store the tokens
keyring.set_password('Box_Auth', 'mybox#box.com', access_token)
keyring.set_password('Box_Refresh', 'mybox#box.com', refresh_token)
def main():
"""Authentication against Box Example"""
# Retrieve tokens from secure store
access_token, refresh_token = read_tokens()
# Set up authorisation using the tokens we've retrieved
oauth = OAuth2(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
access_token=access_token,
refresh_token=refresh_token,
store_tokens=store_tokens,
)
# Create the SDK client
client = Client(oauth)
# Get current user details and display
current_user = client.user(user_id='me').get()
print('Box User:', current_user.name)
if __name__ == '__main__':
main()
I suggest taking a look at the OAuth 2 tutorial. It will help give a better understanding of how OAuth works and what the various parameters are used for.
The redirect URL is set in your Box application's settings:
This is the URL where Box will send an auth code that can be used to obtain an access token. For example, if your redirect URL is set to https://myhost.com, then your server will receive a request with a URL that looks something like https://myhost.com?code=123456abcdef.
Note that your redirect URI doesn't need to be a real server. For example, apps that use a WebView will sometimes enter a fake redirect URL and then extract the auth code directly from the URL in the WebView.
The store_tokens callback is optional, but it can be used to save the access and refresh tokens in case your application needs to shutdown. It will be invoked every time the access token and refresh token changes, giving you an opportunity to save them somewhere (to disk, a DB, etc.).
You can then pass in these tokens to your OAuth2 constructor at a later time so that your users don't need to login again.
If you're just testing, you can also pass in a developer token. This tutorial explains how.
This is the most basic example that worked for me:
from boxsdk import Client, OAuth2
CLIENT_ID = ''
CLIENT_SECRET = ''
ACCESS_TOKEN = '' # this is the developer token
oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=ACCESS_TOKEN)
client = Client(oauth2)
my = client.user(user_id='me').get()
print(my.name)
print(my.login)
print(my.avatar_url)

FlowExchangeError('invalid grant') while authorising token

I am having a problem while using the access token retrieved using the refresh token. I am using python api client for Google doc. I have offline access mode and stored my refresh token in database in the userconsent part. Now using the refresh token, I am also able to retrieve the access token using requests.post. Now when I feed the access token thus retrieved to authenticate in the Flowexchange
self.flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET .... )
self.flow.step2_exchange(accesstoken)
I am getting FlowExchangeError(u'invalid_grant',). Anything I m missing ?
Thanks

Categories

Resources