When building server-side applications that interact with Google APIs (like Drive, Gmail, or YouTube), you cannot rely on the standard "Sign in with Google" pop-up. Instead, you need a mechanism that persists authentication even when you aren't there to click "Allow". This is where Refresh Tokens come in.
Generating a Refresh Token
We will use the Google OAuth 2.0 Playground to manually generate a token once, which we can then save for our application to use indefinitely (or until revoked).
1. Go to https://developers.google.com/oauthplayground.
2. Click the Settings icon (top right). Check "Use your own OAuth credentials" and paste your Client ID and Client Secret from the Google Cloud Console.

3. On the left, select the APIs you want to access. For example, expand "Drive API v3" and select https://www.googleapis.com/auth/drive.
4. Click "Authorize APIs".
5. In Step 2, check the box "Auto-refresh the token before it expires" and click "Exchange authorization code for tokens".
6. Click on Step 2 again to reveal your Refresh Token. Copy this string.
Using the Token in Python
Now that you have the refresh token, you can use it to create an authenticated service without user interaction using the google-auth library.
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
import json
def create_service(CLIENT_SECRET_FILE, REFRESH_TOKEN, SCOPES, API_SERVICE_NAME, API_VERSION):
# Load client config
with open(CLIENT_SECRET_FILE, "r") as f:
data = json.load(f)
CLIENT_ID = data['web']['client_id']
CLIENT_SECRET = data['web']['client_secret']
# Create credentials object using the refresh token
creds = Credentials.from_authorized_user_info(
info={
'refresh_token': REFRESH_TOKEN,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
},
scopes=SCOPES
)
# Build the service
return build(API_SERVICE_NAME, API_VERSION, credentials=creds)
