Search code examples
pythongoogle-classroom

Give access for service account to google accounts in classroom


I want to get access to classroom records from my server application.

I have created a service account, but I can't get records from classroom created from my google account.

How i can get access? Thanks


Solution

  • Creating a service account is not enough. You also have to perform domain wide delegation and impersonate another user in your domain.

    The main purpose of granting domain-wide authority to a service account is for these accounts to be able to access data on behalf of a user in your domain as otherwise the service account acts like just another account and it is trying to access its own data from Classroom.

    Therefore when you create this service account which ends impersonating another user in your domain, it will be able to access the records from Classroom this user can.

    As for doing this, you might benefit from taking a look at this extensive guide here.

    You can see that doing this requires the following things:

    1. Create a Credentials object from the service account credentials and include the scopes needed for your operation:
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly', 'https://www.googleapis.com/auth/classroom.announcements']
    SERVICE_ACCOUNT_FILE = '/path/to/service.json'
    
    credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    1. Delegate the authority and impersonate another user in your domain.
    delegated_credentials = credentials.with_subject('[email protected]')
    

    Please note that you will be able to access the resources this user can. So, if for example, you want to access some resources which are only accessible to the course creator or the admin of the domain, you will have to impersonate the course create or the admin, respectively.

    Reference