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’,
redirect_uri=‘urn:ietf:wg:oauth:2.0:oob’
)

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

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

#Getting and trying bearer code
try:
# 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
webbrowser.open(url)
except Exception as e:
print(“Open the following URL in a browser to authorize:”)
print(url)
#enter with bearer coded
code = input(“Copy and paste the returned code from the browser and press enter:”)
print(code)
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 @anon65155295 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 @anon65155295 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 - #12 by Matt_Bramlage

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

Cheers,

Peter B

This is useful too: OAuth 2 Workflow — Requests-OAuthlib 1.3.1 documentation

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 - #2 by Ross_Grambo

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