Skip to content
Advertisement

Permanent authentication from cloud function

I am trying to host some code inside a cloud function. This code tracks and parses new e-mails and write some information to a Realtime Database. It is almost 100% finished, but as I am very beginner, it’s been hard for me to deal with authentication. From my PC, it all worked when I authenticated just like it is shown here. The problem is that this token.json file, which holds information about my login, is temporary. After some time, it needs to be deleted and I must login again. This login process is a browser tab that opens so I can choose my Google account.

However, my cloud function can’t open browser tabs to login for me. So it must be able to stay logged in forever, or perform the login process without human interference. I feel like Google Dev guides are very unclear, at least for someone as inexperienced as I am. Here is a sample of what I have so far:

scopes = ['https://www.googleapis.com/auth/gmail.readonly']
client_secret_location = 'credentials.json'

def authentication():
    global creds
    creds = None

    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', scopes)

    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)

        with open('token.json', 'w') as token:
            token.write(creds.to_json())

I guess creds is like a object holding my user session. It allows me to build my Gmail API and do all thing I must do with it:

gmail_session = build('gmail', 'v1', credentials = creds)

Howerever, as I said, this token expires after some days and it is needed to login again.

Advertisement

Answer

To enable this so-called server-to-server authentication, you need a service account. If your GMail account is part of a Google workspace, you can find instructions for creating such a service account here: https://support.google.com/a/answer/7378726

As already explained here: Make use of the gmail api through a service account from the server side avoiding the OAUTH2 GUI such service accounts are unfortunately only possible for gsuite (workspace) domains.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement