Content Security Policy (CSP) Error with OAuth Integration in Anvil App

Hi, I am trying to implement oauth flow in anvil. I have used this app as a reference. When I attempt to redirect to OAuth login page from my Anvil app, I get the following error in the browser console:

Refused to frame ‘https://www.oauthapp.com/’ because an ancestor violates the following Content Security Policy directive: "frame-ancestors ‘self’

I have also tried using cross_site_session=True but that doesn’t seem to solve the issue.

I have also tried to open the auth url in a new window using js but it fails to redirect to the callback page.

Below is the snippet of the code:

@anvil.server.callable
def get_oauth_redirect_url():
  """Get the URL that redirects to the Auth0 login page (Step 1)."""

  redirect_url =  "{oauth_uri}?"\
    "client_id={client_id}&"\
    "response_type=code&"\
    "redirect_uri={redirect_uri}&"\
    "scope={scope}&"\
    "state={state}".format(
      oauth_uri=AUTH_URL,
      client_id=anvil.secrets.get_secret('oauth_client_id'),   # Provided by Auth0
      redirect_uri=REDIRECT_URI,
      scope = SCOPE,
      state=STATE,
    )
  return redirect_url
@anvil.server.http_endpoint("/oauth_callback", cross_site_session=True)
def oauth_callback(**kws):
  """Exchange the Authorization code from Step 1 for an Access Token (Step 2).
  
  The Auth0 login page calls this endpoint once the user has logged in.
  """
  print(**kws)
  if 'code' not in kws or 'state' not in kws:
    return "Please make app public to use Auth0."
  
  if kws['state'] == STATE:
    
    url = TOKEN_URL
    data = {
      "grant_type": "authorization_code",
      "client_id": anvil.secrets.get_secret('oauth_client_id'),   # Provided by Auth0
      "client_secret": anvil.secrets.get_secret('oauth_client_secret'),   # Provided by Auth0
      "redirect_uri": REDIRECT_URI,
      "code": kws['code']
    }
    print(data)
    r = requests.post(url, data=data)
    r = r.json()
    
    resp = anvil.server.HttpResponse()
    resp.status = 302
    resp.headers["Location"] = anvil.server.get_app_origin()
    return resp
  else:
    return "Invalid state"

I have registered my app with the redirect_url as: https://myapp/_/api/oauth_callback

and on the client side, I am invoking the code on button click:

  def btn_connect_oauth_click(self, **event_args):
    """This method is called when the button is clicked"""
    auth_url = anvil.server.call('get_oauth_redirect_url')
    anvil.js.window.location.href = auth_url   

Code when I try to attempt to launch the authorize url in new window

  def btn_connect_oauth_click(self, **event_args):
    """This method is called when the button is clicked"""
    auth_url = anvil.server.call('get_oauth_redirect_url')
    anvil.js.window.open(auth_url, "_blank")

With this approach, it directs me to the login page of the app but after successful authentication it does not redirect me to the app back again

Any advice or recommendations on how to resolve this issue would be greatly appreciated. Thank you!

Welcome to the forum!

Are you running this in the IDE? If so, click the three dots next to the Run button and choose to run it in a new tab, so it isn’t running inside an iframe. The iframe the IDE uses to run it inside the IDE messes with things like this.

Hi @jshaffstall ,

Thank you for your reply. When I run in the new tab, it navigates to the oauth app and ask for authorization. However, when I approve teh request, during callback to the anvil app, it is giving me an error. the callback fails with 500 error. There are no logs in the anvil app runtime environment to debug the error,
I have registered the callback url in the app as 'https://myapp/_/api/oauth_callback and my callback function is in the orignal post

Please find the screenshot below:



With that flow the log for the HTTP endpoint call would not be in the IDE log. The HTTP endpoint would have a new server environment spun up for it, so you’d need to look through your app logs for that particular call to see what happened in it.

Typically a 500 error means a compile or runtime error happened.