【问题标题】:Accessing Gmail contacts via the Google People API using service account credentials always returning null使用服务帐户凭据通过 Google People API 访问 Gmail 联系人总是返回 null
【发布时间】:2022-07-14 07:37:57
【问题描述】:

我无法使用以下代码访问 Gmail 联系人。它始终返回 null,并且所有 API 权限都授予帐户内的联系人。

string jsonText = @"{""type"": ""service_account"",
    ""project_id"": """",
    ""private_key_id"": """",
    ""private_key"": """",
    ""client_email"": """",
    ""client_id"": """",
    ""auth_uri"": """",
    ""token_uri"": """",
    ""auth_provider_x509_cert_url"": """",
    ""client_x509_cert_url"": """"
}";

var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(jsonText);

// Credentials
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
    User = credentialParameters.ClientEmail,
    Scopes = new[] { "https://www.googleapis.com/auth/contacts.readonly",
                     "https://www.googleapis.com/auth/contacts",
                     "https://www.googleapis.com/auth/contacts.other.readonly " }
        }.FromPrivateKey(credentialParameters.PrivateKey));

// accessToken
var accessToken = await credential.GetAccessTokenForRequestAsync();

// Create the service.
var service = new PeopleServiceService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
});

GoogleCredential googleCredentials = GoogleCredential.FromJson(jsonText);

var ser = new PeopleServiceService(new BaseClientService.Initializer()
{
    HttpClientInitializer = googleCredentials,
});

// Get list of contacts
ConnectionsResource.ListRequest peopleRequest = ser.People.Connections.List("people/me");

peopleRequest.PersonFields = "names,emailAddresses";
ListConnectionsResponse response = peopleRequest.Execute();
IList<Person> people = response.Connections;

【问题讨论】:

    标签: c# .net gmail google-api-dotnet-client google-people-api


    【解决方案1】:

    旁注:

    无法访问 Gmail 联系人

    目前尚不清楚您是使用标准 Gmail 帐户还是使用 Google Workspace。您应该知道,服务帐户不适用于标准 Gmail 用户的联系人。没有工作空间就无法委派权限。


    请记住,服务帐户不是您。服务帐户是一个虚拟用户。它返回 null 或空,因为您的服务帐户当前没有任何联系人。您需要添加一些。

    但是,如果您尝试访问某个用户的联系人,那么。

    为了让服务帐户访问用户数据,您需要将数据委托给该用户。尝试访问 Google 联系人时,您需要使用您的工作区帐户。工作区管理员可以将domain wide delegation 设置为您域中您想要访问其联系人的用户。

    确保您已包含Domain scope,如文档中所示。

    然后记得在初始化服务帐户时添加用户,这必须是您已为其设置委托的域中的用户。

    var serviceAccountCredentialInitializer = new  ServiceAccountCredential.Initializer(serviceAccount)
    {
        User = gsuiteUser,
        Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }
    
    }.FromCertificate(certificate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2021-09-05
      • 2019-01-10
      • 1970-01-01
      相关资源
      最近更新 更多