There are many posts dealing with redirect_uri
issues for accessing Google APIs, but I have not been able to find one that directly addresses my particular situation.
Specifically, I am trying to access the Google Search Console API from Jupyter Lab. When testing in iPython via iTerm, this example from the Google Docs team worked like a charm. Now that I've switch the code to a notebook though, I'm running into this issue:
Authorization Error Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:65490/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs [...]
I've followed the instructions from other posts to add a generic localhost
to my authorized redirect URIs like so:
{
"web":{
"client_id":"[...]",
"project_id":"[...]",
"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":"[...]",
"redirect_uris":[
"http://localhost"
]
}
}
In my code I've even included this in the kwargs
of the from_client_secrets_file
method which I think this documentation says is ok:
def prepare_credentials():
creds = None
if os.path.exists(SECRETS_PATH + 'token.pickle'):
with open(SECRETS_PATH + 'token.pickle', 'rb') as token:
creds = pickle.load(token)
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(CLIENT_SECRETS, SCOPES,redirect_uri='http://localhost')
creds = flow.run_local_server(port=0)
with open(SECRETS_PATH + 'token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
The interesting thing I've noticed is that while I am interacting with Jupyter Lab at http://localhost:8889/lab
, the redirect_uri
this code randomly changes the port in the redirect_uri
. So for example if I run the code once, it will try http://localhost:65490/
, but if I run it again I might get http://localhost:51648/
(and so on...). Also, I don't know if this matters, but I'm running Jupyter Lab in Chrome, whereas my default browser (and where I am logged in to the Google profile I use for this work) is Firefox. The flow opens Firefox, but I am stuck at this 400 error...