I am trying to add members to google group using the python script as shown below. I am using a service account to add members to a group. However, I am getting the below error:
Error:
An error occurred: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})
python script:
from google.oauth2 import service_account
from pathlib import Path
from googleapiclient.discovery import build
import os
BASE_DIR = Path(__file__).resolve().parent
CREDENTIAL_PATH = os.path.join(BASE_DIR, "python-demo-project-service-account.json")
print(CREDENTIAL_PATH)
# Path to your service account key file
SERVICE_ACCOUNT_FILE = CREDENTIAL_PATH
# The email of the Google Group to modify
GROUP_EMAIL = 'email.com'
# The email of the user to add to the group
USER_EMAIL = '[email protected]'
# Scopes required for the Directory API
SCOPES = ['https://www.googleapis.com/auth/admin.directory.group.member']
def add_user_to_group(service_account_file, group_email, user_email):
credentials = service_account.Credentials.from_service_account_file(
service_account_file, scopes=SCOPES)
# You need to specify the subject email if you're using domain-wide delegation
# This is the email of a user in the domain with sufficient permissions to add members to a group
delegated_credentials = credentials.with_subject('[email protected]')
service = build('admin', 'directory_v1', credentials=delegated_credentials)
member = {
'email': user_email,
'role': 'MEMBER'
}
try:
result = service.members().insert(groupKey=group_email, body=member).execute()
print(f'Added {user_email} to {group_email}: {result}')
except Exception as e:
print(f'An error occurred: {e}')
# Add a user to the group
add_user_to_group(SERVICE_ACCOUNT_FILE, GROUP_EMAIL, USER_EMAIL)
Can someone help me what permissions my service accounts needs or am I missing something.