code": 403, "message": "Not Authorized to access this resource/api

883 Views Asked by At
GET https://admin.googleapis.com/admin/directory/v1/groups/{groupKey}/members

I'm unable to make this HTTP call.

here's my code is

from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.auth.exceptions import RefreshError
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
import requests

# Load the service account credentials
credentials = service_account.Credentials.from_service_account_file(
    '/home/key.json',
    scopes=['https://apps-apis.google.com/a/feeds/groups/'
]
)

# Check if the credentials have an access token or if it's expired
if not credentials.token or credentials.expired:
    try:
        # Refresh the access token using the credentials
        credentials.refresh(Request())
    except RefreshError:
        raise Exception('Failed to refresh access token')

# Get the access token from the credentials
access_token = credentials.token
print(access_token)

group_key = "[email protected]"

# Set the API endpoint URL
url = f"https://admin.googleapis.com/admin/directory/v1/groups/{group_key}/members"

# Set the access token in the Authorization header
# access_token = "your_access_token_here"
headers = {"Authorization": f"Bearer {access_token}"}

# Make the HTTP GET request to the API endpoint with the headers
response = requests.get(url, headers=headers)

# Check if the response was successful
if response.status_code == 200:
    # Get the list of members from the response JSON
    members = response.json().get("members", [])

    # Print the list of members
    for member in members:
        print(member["email"])
else:
    # Print the error message if the response was not successful
    print(f"Error: {response.status_code} - {response.text}")

I'm getting this error Error: 403 - { "error": { "code": 403, "message": "Not Authorized to access this resource/api", "errors": [ { "message": "Not Authorized to access this resource/api", "domain": "global", "reason": "forbidden" } ] } }

The service account has these roles BigQuery Resource Viewer, Folder Viewer,Organization Viewer,Viewer.

1

There are 1 best solutions below

0
Sai Chandra Gadde On

As you have stated that when you try using the browser, you can see the output as expected, so try to follow the troubleshooting steps mentioned below:

  1. Add the following scopes in the workspace admin console for the service account: 'https://www.googleapis.com/auth/admin.directory.group.readonly', 'https://www.googleapis.com/auth/admin.directory.group.member.readonly'

  2. Check whether the Admin SDK is enabled and the User has an Admin role.

  3. Try setting up domain-wide delegation for service accounts by using this official document.

Check for typo mistakes in domain and group names.

Attaching the similar issue for your reference.