Oauth redirects to localhost when hosted on server

Question:

I hope you can help.

This script works locally for Google Analytics Auth, but when I put it on my server & run it with python3 xxx.py and go to the auth URL it redirects to localhost, which fails because it’s on the server.

Does anyone have any idea why?

or even a nice Python example of connecting to Google Analytics. I’ve researched a lot & I couldn’t get the examples I’ve seen working.

import pandas as pd
import requests
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
flow = InstalledAppFlow.from_client_secrets_file('./client_secret.json', SCOPES)
creds = flow.run_local_server(port=0)
Asked By: kikee1222

||

Answers:

Its not working because you followed an example for authenticating with an installed application

InstalledAppFlow

Will open the authorization web browser window on the machine its running on. if you intend to host this on a website to allow users to access their google analytics data you will need to use web browser credentials and the code for authenticating with a web browser.

Oauth2 web application

The only sample i have been able to find for that is for the YouTube api you will need to alter it for Google anltyics

@app.route('/authorize')
def authorize():
  # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow
  # steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
  authorization_url, state = flow.authorization_url(
      # This parameter enables offline access which gives your application
      # both an access and refresh token.
      access_type='offline',
      # This parameter enables incremental auth.
      include_granted_scopes='true')

  # Store the state in the session so that the callback can verify that
  # the authorization server response.
  flask.session['state'] = state

  return flask.redirect(authorization_url)

The full sample can be found here

service account.

If you will only be accessing your own data and not the data owned by others then you should consider using a service account. Hello Analytics Reporting API v4; Python quickstart for service accounts

this uses

 credentials = ServiceAccountCredentials.from_json_keyfile_name(
  KEY_FILE_LOCATION, SCOPES)
Answered By: DaImTo