【问题标题】:Getting All Users and Mailboxes with One API使用一个 API 获取所有用户和邮箱
【发布时间】:2021-08-25 21:26:57
【问题描述】:

我正在支持一名 IT 管理员,他本人也在促进合规性软件的使用。为此,我编写了一些 C# 代码来遍历目录中的所有用户,并对他们的消息执行操作。我当前的解决方案使用两种不同的 API 来实现这一点(下面的代码 sn-p),但显然最好只使用一个 API。浏览了此处的其他帖子后,我未能找到关于如何实现这一目标的令人满意的明确答案。我的应用是一个服务帐号,启用了 Google Workspace 域范围的委派。如何只使用一个 API 来完成我使用两个 API 所做的事情?

[工作代码sn-p]

string domain; // domain name
string adminEmail; // admin e-mail
string directoryClientEmail; // client e-mail for Directory API
string directoryPrivateKey; // private key for Directory API
string directoryPrivateKeyId; // private key ID for Directory API
string gmailClientEmail; // client e-mail for Gmail API
string gmailPrivateKey; // private key for Gmail API
string gmailPrivateKeyId; // private key ID for Gmail API
CancellationToken cancellationToken; // a cancellation token

DirectoryService directoryClient = new DirectoryService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(creds.DirectoryClientEmail)
            {
                User = adminEmail,
                Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
                Key = RSA.Create(directoryPrivateKey),
                KeyId = directoryPrivateKeyId
            }.FromPrivateKey(directoryPrivateKey))
    });

UsersResource.ListRequest userListRequest = directoryClient.Users.List();
userListRequest.Domain = domain;
Users userList = await userListRequest.ExecuteAsync(cancellationToken);

foreach (User user in userList)
{
    GmailService gmailClient = new GmailService(
        new BaseClientService.Initializer
        {
            HttpClientInitializer = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(gmailClientEmail)
                {
                    User = user.PrimaryEmail,
                    Scopes = new[] { GmailService.Scope.MailGoogleCom },
                    Key = RSA.Create(gmailPrivateKey),
                    KeyId = gmailPrivateKeyId
                }.FromPrivateKey(gmailPrivateKey))
        });

    ListRequest listRequest = new ListRequest(gmailClient, "me");
    ListMessageResponse listMessageResponse = await listRequest.ExecuteAsync(cancellationToken);

    foreach (Message message in listMessageResponse.Messages)
    {
        // do stuff
    }
}

【问题讨论】:

    标签: c# .net-core google-api gmail-api google-authentication


    【解决方案1】:

    要实现您想要的,您不能只使用一种 API。由于 Gmail API 不会为您提供域中的用户,但您可以使用它获取用户的消息;你需要的。所以 Gmail API 是一个要求。

    如果你想要一个最新的域用户列表,那么你需要使用 Directory API,所以除非你在其他地方有用户列表,否则你也需要这个 API。

    【讨论】:

    • 有没有办法拥有一组授权使用两个 API 的凭据?
    • 是的,如果为同一个 GCP 项目启用了两个 API,则该项目的凭据将适用于启用的两个(以及任何其他)API。
    猜你喜欢
    • 2011-06-03
    • 2015-04-07
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多