Query shared drive organizers from Google Workspace

Posted 2023-03-21 09:00:00 by sanyi ‐ 3 min read

Query the list of shared drives and their organizers from Google Workspace using .NET / C#

A few days ago I got the task to collect the list of all shared drives and their organizers (managers) from our Google Workspace account. The Google Workspace user interface is useless for this task, there is no way to export the required information, so I went to the Google Drive API.

Nowadays I'm experimenting with .NET / C# (I ignored it in the past because of its Microsoft origins and the dependence on Windows, but things have changed a lot in Redmond in the last few years), so I selected C# for this job.

The first thing we need to talk to the Google Drive API is a Service Account. Go to console.cloud.google.com, create a project then select APIs & Services > Credentials from the left sidebar. Click the CREATE CREDENTIALS button, select Service Account and create one. We don't have to grant any access to it for now. After creation go back to the list of Service Accounts and note the Email of the newly created service account, we will need it later. Select the new Service Account from the list, go to the KEYS tab and click Add Key > Create new key. Select the JSON format and save the resulting file as credentials.json.

Now go back to the DETAILS tab and open Advanced Settings, Domain-wide Delegation. Save the Client ID displayed there and click VIEW GOOGLE WORKSPACE ADMIN CONSOLE to switch to admin.google.com. There go to Security > Access and data control > API controls, MANAGE DOMAIN VIEW DELEGATION and click API client > Add new. Fill in the Client ID saved in the previous step and add the following OAuth scopes:

  • https://www.googleapis.com/auth/admin.directory.user
  • https://www.googleapis.com/auth/drive

The first one is not strictly required, but it may be useful if you need to fetch some other data later. Finally click AUTHORIZE.

Next clone the repository from here: github.com/sapati/GoogleSharedDrives

Copy the credentials.json file to the project directory and open appsettings.json. In the Settings section set the following values:

  • ServiceAccountID: the Email of the newly created Service Account from console.cloud.google.com
  • AdminEmail: email address of the Google Workspace administrator our client will impersonate
  • CustomerID: you can find it on admin.google.com, Account > Account Settings > Profile
  • Domain: the primary domain of your Google Workspace account

The required framework for this project is .NET 7.

Now all you need to do is to run dotnet build and dotnet run.

The code does not implement pagination for the permissions, but if you have more than a 100 users assigned directly to a Shared Drive (not via a Group) then you may need it. In that case simply follow the same way as the drive list pagination.

Tags:
dotnet .net c# drive google workspace