Hi all,
I’m a newbie to Anvil, APIs, OAuth and lots of things in general, and I would greatly appreciate some assistance regarding my current dilemma.
What I’m trying to do:
I’m trying to authenticate with a third-party api using OAuth2. I found this great example of Anvil OAuth application, and I used it as my starting point:
https://anvil.works/build#clone:XQZFL5OYXDIBOA5Y=FSY65DSKQ4GMV2ME2U3LX7LK
What I’ve tried and what’s not working:
In the first step of the process, I make an api request to get the code that I need to exchange for a bearer token. I set the callback url in my third-party application and have used the @anvil.server.http_endpoint decorator to create my endpoint url. I can see in my browser that the third-party application returns the code as a parameter in the callback url and the callback url appears correct in the form of https://[my_anvil_app_url]/callback. However, instead of showing any response in the browser window, I see this error message:
I added the cross_site_session paramater in the decorator to see if it would make any difference, but it didn’t.
This is the current code in my server module:
import anvil.secrets
import anvil.server
import string
import anvil.http
import requests
import json
OAUTH_URI = "https://[third_party_host]"
CALLBACK_URI = "https://[my_anvil_app]/callback"
@anvil.server.callable
def get_oauth_redirect_url():
url = "{oauth_uri}/oauth/authorize?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}".format(oauth_uri=OAUTH_URI,client_id=anvil.secrets.get_secret('a2j_app_key'),redirect_uri=CALLBACK_URI,)
return url
@anvil.server.http_endpoint("/callback", cross_site_session=True)
def callback(**kws):
print("code: " + kws['code'])
if 'code' not in kws:
return "Please make app public to use Auth0."
url = "{oauth_uri}/oauth/token".format(oauth_uri=OAUTH_URI)
data = {
"grant_type": "authorization_code",
"client_id": anvil.secrets.get_secret('a2j_app_key'), # Provided by Auth0
"client_secret": anvil.secrets.get_secret('a2j_app_secret'), # Provided by Auth0
"redirect_uri": CALLBACK_URI,
"code": kws['code']
}
r = requests.post(url, data=data)
r = r.json()
print (r['access_token'])
print (r['refresh_token'])
resp = anvil.server.HttpResponse()
resp.status = 302
resp.headers["Location"] = anvil.server.get_app_origin()
return resp