Göran
Göran

Reputation: 98

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...

Upvotes: 1

Views: 543

Answers (2)

Hans Z.
Hans Z.

Reputation: 53948

I believe that is supported as described in https://github.com/dart-lang/googleapis_auth#autonomous-application--service-account. With version 0.2.3 the constructors for ServiceAccountCredentials now have the optional named argument impersonatedUser which can be used to set the user to impersonate.

import "package:http/http.dart" as http;
import "package:googleapis_auth/auth_io.dart";

var accountCredentials = new ServiceAccountCredentials.fromJson({
  "private_key_id": "<please fill in>",
  "private_key": "<please fill in>",
  "client_email": "<please fill in>@developer.gserviceaccount.com",
  "client_id": "<please fill in>.apps.googleusercontent.com",
  "type": "service_account"
}, impersonatedUser: '[email protected]');
var scopes = [...];

...

var client = new http.Client();
obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client)
    .then((AccessCredentials credentials) {
  // Access credentials are available in [credentials].
  // ...
  client.close();
});

Upvotes: 0

sgjesse
sgjesse

Reputation: 4628

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));
    });
  });
}

Upvotes: 1

Related Questions