0
votes

I am just starting out with the c# Google.Apis.Gmail.V1 classes and using a service account to read a mailbox.

My code works fine when I use the following snippet

 ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(ServiceAccountEmailAddress)
           {
               User = "[email protected]",
               Scopes = new[] { "https://www.googleapis.com/auth/gmail.readonly" }
           }.FromCertificate(certificate));

With that code I can call the following successfully

if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
        {
}

But I need to modify the email messages so I changed the scope from

https://www.googleapis.com/auth/gmail.readonly

to

https://www.googleapis.com/auth/gmail.modify

I now get an exception when requesting the access token

{"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""}

I have checked the service account (*.iam.gserviceaccount.com) in the Google Developers Console and I have tried all options for permissions including OWNER which should give me Full access to all resources but no joy.

I think I am just missing a simple step but I am unsure of where to look next.

1

1 Answers

1
votes

TL;DR

I would read through this, but here is the short version. I know this is an older post, but hopefully it finds you!

If you have not updated/white-listed the service account's privileges/scopes in the Google Admin Console you will need to do that, make sure the domain has API access enabled, make sure the service account is setup properly, when creating the "certificate" object be aware its parameters so that it is being instantiated correctly, check the permissions on the account being impersonated and finally make sure you've made an appropriate Google Apps service account key (could have easily made an inappropriate key type.)

White-listing Google APIs in the Admin Console

This gives the Google Apps service account the abilityto use whatever scopes you provide in your Google Apps domain.

  1. Login to the Google Apps Admin Console by using the following link. https://admin.google.com/
    • The Google Apps user account must have sufficient privileges to modify domain related settings. It does not have to be the account used to create the Google Apps project in the developer console. If the account does not have privilege you will be directed to a completely different screen with no options to click on varying domain controlling web apps like "Security", "Roles", "Support", "Groups" and etc. Instead you'll dumped onto a page that shows things like "Gmail", "Drive", "Docs" and etc. that is typical user apps. The current link it drops you at is https://apps.google.com/user/hub
  2. Click “Security.”
  3. Click “Show more” option at the bottom of the security options list.
  4. Click “Advanced Settings” to get the more options.
  5. Select the “Manage API client access” link.
  6. Now certain API scopes must be white-listed for the desired service account. In the “Client Name” text box provide the service account’s client ID. The client ID is obtained in the developer console. In the “One or more API scopes” add the desired scopes; comma delimited.

    Note, if there are existing scopes they will be removed so be sure to re-add any that will be needed.

Enable Domain Wide API Access

  1. Login to the Google Apps Admin Console by using the following link. https://admin.google.com/
  2. Go to the “Security” page.
  3. Under “API reference” section
  4. Make sure that “Enable API access” is enabled.

Creating an Appropriate Google Apps Service Account Key (Probably this)

  1. Go to the Google Developer Console. Login as the Google Apps user that created the Google Apps project/service account. https://console.developers.google.com/
  2. Navigate to the particular project with which you created the service account.
  3. Click the "Service Account" button on the left of the project's page to bring up a page with all of the project's service accounts.
  4. Click the vertical ellipse widget all the way to the right of the desired service account's row. Select “Create Key.”
  5. Select .p12 key as it looks like this is what you're trying to use. Click "Create." Be sure to protect this key.

I have found that if the key is not created this way then it leaves open the possiblity for making either an API key or an OAuth 2.0 client/user key. These are the wrong types of keys to use in this case you would need to have created a service account key. The way outlined above forces you to create a service account key.

Modifying the Existing Google Apps Service Account's Settings

I'm not going over how to setup the actual service account, one thing you may need in your case is to make sure that the service account has domain wide delegation enabled. This is toggled in the Google Developer Console. Should be pretty easy to find.

Code

You do not provide your entire code base for creating the token, so just want to add a few things you might be doing improperly.

  1. Make sure when you create the certificate that the secret you provide is the default "notasecret" string. This secret is currently the default value provided by all keys distributed by Google and is immutable during key creation. I had a link to prove this, but have since lost it.

    X509Certificate2 certificate = new X509Certificate2(certificateFilePath, "notasecret", X509KeyStorageFlags.Exportable);
    
  2. Just trying to advocate proper coding. While I have found some bugs in the past with Google's constant values that required additional string manipulation (adding additional slashes.) You should really be using the string constants that they provide in place of literals. I only say to use these because it provides a layer of abstraction, who is to say Google will never change the literal; unlikely.

In your case the new scope is:

GmailService.Scope.GmailModify

While the old scope was:

GmailService.Scope.GmailReadonly

Otherwise, everything code wise looks good to me.


Another thing to try would be to make sure that the actual Google Apps user account being impersonated by the service account has sufficient privileges. I would suspect a different error if this were the case, would be getting a 403 in the response instead. Anyway, in your case this is the "[email protected]" account. Once again you would go to the Google Admin Console, check its roles make sure it has sufficient roles checked for whatever it is you're trying to do. I don't know what specifically you'll need in this case, best bet would be to give it the same permissions as the "Super Admin" role then remove permissions as you go to see what it might actually need. Otherwise, if possible just give it "Super Admin."


If I was a gambler I would put my money on an inappropriately created service account key. I just recently ran into this and it was the only thing that produced the same exact error you're receiving. Other things would get me the same "Description" value in the response token, but not the same "Error" value. I'm not really even sure how the culprit key was made, because I didn't make it. I just know the fix was to recreate a new key with the steps above and that fixed the issue.