Search code examples
dartgoogle-oauthgoogle-admin-sdk

Using Dart googleapis_auth (0.2.2) to authorize Admin SDK Directory API in Google Apps domains with service account


I would like to authorize access to Admin SDK Directory API in Google Apps domains with a service account. As I understand it requires a JWT claim with a sub field and I can't find that in the pub package googleapis_auth (0.2.2).

If it's missing:

Is there a workaround? Will it be included in a future version?

For the time being I'm getting along with an installed app authorizing with user consent (admin account) but it's a bit tedious...


Solution

  • With version 0.2.3 of googleapis_auth the constructors for ServiceAccountCredentials have the optional named argument impersonatedUser which can be used to set the user to impersonate.

    The code for listing all users using the Admin SDK Directory API in Google Apps domains with a service account, on behalf of the admin user [email protected] looks like this:

    import 'package:googleapis/admin/directory_v1.dart';
    import 'package:googleapis/drive/v2.dart';
    import 'package:googleapis_auth/auth_io.dart';
    
    final credentials = new ServiceAccountCredentials.fromJson({
      "private_key_id": "<please fill in>",
      "private_key": "<please fill in>",
      "client_email": "<please fill in>",
      "client_id": "<please fill in>",
      "type": "service_account"
    }, user: '[email protected]');
    
    const SCOPES = const [AdminApi.AdminDirectoryGroupScope,
                          AdminApi.AdminDirectoryUserScope];
    void main() {
      clientViaServiceAccount(credentials, SCOPES).then((http_client) {
        var admin = new AdminApi(http_client);
        admin.users.list(domain: 'domain.com').then((Users users) {
          users.users.forEach((user) => print(user.name.fullName));
        });
      });
    }