簡體   English   中英

使用服務帳戶憑據通過 Google People API 訪問 Gmail 聯系人始終返回 null

[英]Accessing Gmail contacts via the Google People API using service account credentials always returning null

我無法使用以下代碼訪問 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;

邊注:

無法訪問 Gmail 聯系人

目前尚不清楚您是使用標准 Gmail 帳戶還是使用 Google Workspace。 您應該知道服務帳戶不會與標准 Gmail 用戶的聯系人一起使用。 沒有工作空間就無法委派權限。


請記住,服務帳戶不是您。 服務帳戶是一個虛擬用戶。 它返回 null 或空,因為您的服務帳戶當前沒有任何聯系人。 你需要添加一些。

但是,如果您嘗試訪問用戶的聯系人,那么。

為了讓服務帳戶訪問用戶數據,您需要委派給該用戶。 嘗試訪問 Google 聯系人時,您需要使用您的工作區帳戶。 工作區管理員可以為您想要訪問其聯系人的域上的用戶設置域范圍的委派

確保您已包含文檔中顯示的域范圍

然后記得在初始化服務帳戶時添加用戶,這必須是您已為其設置委派的域中的用戶。

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

}.FromCertificate(certificate);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM