I am using google_auth_oauthlib.flow
in Python to authorize Google Oauth 2 account.
My code looks like this:
from google_auth_oauthlib.flow import InstalledAppFlow
flow = InstalledAppFlow.from_client_secrets_file(
"client_secret_929791903032.apps.googleusercontent.com.json",
scopes=['profile', 'email'])
flow.run_local_server(open_browser=False)
session = flow.authorized_session()
profile_info = session.get(
'https://www.googleapis.com/userinfo/v2/me').json()
print(profile_info)
Basing on run_local_server()
document, I tried to set open_browser=False
but then Google provided me an URL to authorize, it looks like this https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=929739191032-hpdm8djidqd8o5nqg2gk366efau34ea6q.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=profile+email&state=oHJmupijpVH2gJEPqTogVVHIEtbVXcr&access_type=offline
After clicking to the provided link, my browser automatically opened with the UI named Sign in with Google, then I have to sign in manually on the browser.
So my question is how to open the authorization URL without opening browser? I want my code automatically authorize without doing manually.
So my question is how to open the authorization URL without opening browser? I want my code automatically authorize without doing manually.
If you are using G Suite, you can create a service account and enable Domain Wide Delegation to assume the identity of a G Suite user. This only works for users that are part of your G Suite domain.
If you are not using G Suite, you cannot bypass the user authentication screen the first time a user comes to your website. Once a user authenticates with offline
access, you can save the Refresh Token to use in the future.
Authentication and Authorization is between the client (user) and Google Accounts. Your software is not involved in the credentials part (username, password, etc.). The user must grant permission to Google Accounts to allow your services to access the user's Google Identity.
[EDIT 1/22/2019 - after question on how to save the refresh token]
The following code with authorize and save the refresh token:
# pip install google-auth-oauthlib
from google_auth_oauthlib.flow import InstalledAppFlow
# https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'])
cred = flow.run_local_server(
host='localhost',
port=8088,
authorization_prompt_message='Please visit this URL: {url}',
success_message='The auth flow is complete; you may close this window.',
open_browser=True)
with open('refresh.token', 'w+') as f:
f.write(cred._refresh_token)
print('Refresh Token:', cred._refresh_token)
print('Saved Refresh Token to file: refresh.token')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With