'Safari can't open the page localhost:random_port

I followed the instructions on Google API quickstart Python so that I can get started quickly. I downloaded the JSON file set with the default name and as a Desktop App. After making sure the each Python library was up to date, I pasted and ran the code on the page.

What happens after many tries is the following:

  1. A browser tab will open
  2. I will be asked to choose an account
  3. I then get the screen where I am asked to allow access

View your Google Spreadsheets

  1. I click Allow and wait
  2. I then get a screen that tells me

Safari can't open the page localhost:random_port ... &scope=https://www.googleapis.com/auth/spreadsheets.readonly

To make sure that there are no issues, I added the client ID to the list of allowed connections on admin.google.com, but that didn't seem to help.

Does anyone know what could be causing this issue?

Is there something else I need to do on admin.google.com?

I am using VS Code on Mac. My library versions are

google-api-core          1.23.0
google-api-python-client 1.12.4
google-auth              1.22.1
google-auth-httplib2     0.0.4
google-auth-oauthlib     0.4.1
googleapis-common-protos 1.52.0

For reference, here's the code from the top link that I am trying to use.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))

if __name__ == '__main__':
    main()


Solution 1:[1]

The port you use in the following statement in the code:

flow.run_local_server(port=0)

should be exactly the same as the one you allow in the consent screen for that project.

Make sure the JS redirect URL points to the same port you will be serving from locally.

See google_auth_oauthlib.flow for more information about the module.

Solution 2:[2]

For anyone else having this issue. The issue is related to the OS/software on OS. I had no issues running this on a fresh install of Mac OS.

Solution 3:[3]

Just Ran into the same question.
If you use Safari, it will try to access to https://localhost:xxxx/xxxx instead.
Pasting the url to another browser such as Chrome works fine.

to stop Safari keeps forcing HTTPS on localhost, go to (Safari > Preferences > Privacy > Manage Website Data...)
Search for localhost and press Remove.

Try the script again to see if it works.

Solution 4:[4]

In my MacOS settings I changed my default browser to Google Chrome, and this same authentication flow began working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aerials
Solution 2 cpuser
Solution 3 Peien Wang
Solution 4 PhlipPhlops