API authorization in python

Hello! I’m trying to get some boards information from a asana project and I need to run (update) the script all day long. However I’m trying to authorize wiith OAuth2 (with client ID and client secret) but the authorization returns failed. When I try to authorize with bearer code the script can authorize and access the information needed. But the bearer code need to be refreshed once a hour, and I need to run this code all day long. Is there other way to authorize the script?

Python code:

#OAuth2 credentials
client = asana.Client.oauth(
client_id= ‘ID’,
client_secret=’ SECRET’,

#Try to authorize
(url, state) = client.session.authorization_url()

#here returns unauthorized
print(“authorized=”, client.session.authorized)

#Getting and trying bearer code
# in a web app you’d redirect the user to this URL when they take action to
# login with Asana or connect their account to Asana
import webbrowser
except Exception as e:
print(“Open the following URL in a browser to authorize:”)
#enter with bearer coded
code = input(“Copy and paste the returned code from the browser and press enter:”)
token = client.session.fetch_token(code=code)

exchange the code for a bearer token

os.environ[‘ASANA_TOKEN’] = json.dumps(token)

#here returns authorized
print(“authorized=”, client.session.authorized)

Hi @Matheus_Damasceno and welcome to the forum!

There is not another way using OAuth. But if you’re just accessing your one account, you should be able to use a Personal Access Token instead - much simpler.

1 Like

Hi @Matheus_Damasceno I have exactly the same issue (see OAuth avoid user interaction?)

After much reading it appears the Refresh token is the way to go. I can’t use a Personal since this is an end-user tool so each user needs to access on their own merits.

Sadly I can’t find examples of dealing with the Refresh token via the Python API.

There is this: Get refresh token

which is exactly what I (and likely you) are hoping to do :slight_smile:


Peter B

This is useful too: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#refreshing-tokens

The pieces are there… it’s just putting them together and I don’t have the background in OAuth to intuitively come up with the code…

Thanks, Peter!
I will see it :smiley:

Unfortunately it turns out the Asana Python library doesn’t natively handle Refresh tokens yet :frowning: SEe Python API: check if authentication is still valid

@Matheus_Damasceno if you happen to figure it out using raw oauthlib please let us know :slight_smile: