Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OAuth on localhost and pythonanywhere

I am making a calender app which allows users to give permission to access their google calendars and then my app will allow them to view and edit their calendars displayed in my own custom style.

It is based on this Google "quickstart" sample.

It currently works fine locally, but I have failed so far to get it to run when hosted on pythonanywhere.com (where the URL will be http://myname.pythonanywhere.com).

With my working local version, the credentials.json file I am using starts with "installed": which AFAICT corresponds to a "Desktop App" and the "redirect_uris": contains ["urn:ietf:wg:oauth:2.0:oob", "http://localhost”]. (The "http://localhost" makes sense but I have no idea why there is a second uri "urn:ietf:wg:oauth:2.0:oob")

{
    "installed": {
        "client_id": "XXXXXXXXXXXXXXXX.apps.googleusercontent.com",
        "project_id": "my_great_calendar",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "XXXXXXXXXXXXX",
        "redirect_uris": [
            "urn:ietf:wg:oauth:2.0:oob",
            "http://localhost"
        ]
    }
}

Correct me if I'm wrong, but I assume that this credentials.json file can't possibly work when hosted at myname.pythonanywhere.com and I will need to create a new one (on Google's "APIs and Services" page) made by declaring the project as a "web application"? and telling google my redirect uri is "http://myname.pythonanywhere.com"?

If there was a way to have a single credentials.json file that would work both locally and on pythonanywhere?

EDIT: The quickstart sample employs InstalledAppFlow.from_client_secrets_file which I now think is wrong. it might need to somehow employ google_auth_oauthlib.flow.Flow.from_client_secrets_file() instead.... as described here.

like image 388
Mick Avatar asked Nov 07 '22 07:11

Mick


1 Answers

You can have a single Client ID / Client Secret pair that supports multiple redirect URIs fine:

  • Go to APIs and Services
  • Go to Credentials
  • Find your client ID
  • Click Edit (pencil icon)
  • Under "Authorized redirect URIs" you can add more of them.
  • Save

The JSON will then contain the two redirect URIs. I don't know how their library picks which one to use, so you probably want to explicitly specify it, by passing a redirect_uri param:

flow = Flow.from_client_secrets_file('client_secrets.json', redirect_uri='http://blah.pythonanywhere.com/')

To know which one to use, you can either pass some configuration when starting your server (such as an environment variable or command line flag), or make your server detect it automatically looking at the Host header.

like image 93
Dirbaio Avatar answered Nov 17 '22 21:11

Dirbaio