google-api-dotnet-client: Impersonation using Service account not working in dot net

I have looked into the Service account sample to access public post in google plus account. Similarly I am trying to use the service account which is having domain wide delegation to impersonate a user and scan through the email id in a G-Suite account. When I try to call the Gmail API I am getting unauthorized_client exception. Could you please help me to understand what I am missing here? Details of the google console setting and the code snippet is defined below. • Enabled Domain-Wide Delegation for the service account

1

• Enable the client to access the API in security settings

2

• Following is the code and the error message which I got in a console application. `public static void AccessGmailInboxWithServiceAccount() {

        String serviceAccountEmail = lstrServiceAccountId;//"SERVICE_ACCOUNT_EMAIL_HERE";

        var certificate = new X509Certificate2(p12KeyFilePath, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
               User = impersonateUserEmail,
               Scopes = new[] { GmailService.Scope.MailGoogleCom }
           }.FromCertificate(certificate));


        // Create the service.
        var gmailService = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail API Service Account Sample Impersonating User",
        });

        var listRequest = gmailService.Users.Messages.List(impersonateUserEmail);
        listRequest.Q = "in:INBOX";
        var messages = listRequest.Execute().Messages;

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }` 

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 20 (4 by maintainers)

Most upvoted comments

@AbilashSekharan I don’t know much about delegation, but have noticed a couple of things that might help:

  • This SO question/answer does suggest that your domain-wide delegation is mis-configured somehow. This github issue may also help; it’s about Ruby, rather than C#, but appears to match what you’re seeing and some of the solutions shown are language-agnostic.
  • In the latest code you’ve shown, where you’re trying to access the calendar API, it looks like you’re still requesting the gmail scope which won’t work.