Search code examples
google-cloud-platformoauth-2.0google-oauthgoogle-cloud-shell

How to run flow.InstalledAppFlow run_local_server() from a google cloud shell?


I run some CLI python code from the cloud terminal. The code calls "google_auth_oauthlib" library.

    auth_flow = flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file=client_secret_json_file_fath, scopes=scopes)
    auth_flow.run_local_server()

I get in the cloud terminal an authentication url to click on. I pass the consent screen and I'm redirected to a localhost in the browser, which obviously cannot be resolved.

How can I get the secrets from google-cloud terminal?

enter image description here


Solution

  • What you should do is something like this.

    def build_service(credentials, scope, user_token):
        creds = None
    
        if os.path.exists(user_token):
            creds = Credentials.from_authorized_user_file(user_token, scope)
    
        # If there are no (valid) user credentials available, prompt the user to 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, scope)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open(user_token, 'w') as token:
                token.write(creds.to_json())
        try:
            return build('drive', 'v3', credentials=creds)
        except HttpError as error:
            # TODO(developer) - any errors returned.
            print(f'An error occurred: {error}')
    
    # Get an authorized Google Drive service object.
    google_api_service = build_service(APPLICATION_CREDENTIALS, SCOPES, USER_TOKENS)
    

    If you run this code on your machine once. It will store the refresh token in the user_tokens file. then you can upload it to your cloud server and when it runs it will use that token file.

    although it would probably be easer to use a service account if you can.