'Google API (Gmail) failing with failed precondition 400

I am trying to use the google APIs to read emails and I'm repeatedly failing to get good results. It is supposed to be a server->server account that runs periodically in the background, but I can't get it to connect. The code is basic:

GoogleCredential credential;
using (var stream = new FileStream("Content/service_credential.json", FileMode.Open, 
                                   FileAccess.Read))
{
    credential = GoogleCredential.FromStream(stream);
    credential = credential.CreateScoped(new[] { GmailService.Scope.GmailModify });
}

var service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "try-apis",
});


ListLabelsResponse response = service.Users.Labels.List("me").Execute();
foreach (Label label in response.Labels.OrderBy(p => p.Name))
{
    Console.WriteLine(label.Id + " - " + label.Name);
}

Console.Read();

Error:

Additional information: Google.Apis.Requests.RequestError

Bad Request [400]

Errors [

    Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]

]

In IAM settings, the account I'm using has full permissions:

enter image description here

The account has full permissions:

enter image description here

Likewise, more full permissions:

enter image description here

What am I missing? I can't find any representative .Net requests that make sense in just connecting to an in box.



Solution 1:[1]

I had this same issue. XLSX documents uploaded into Google Drive (Sheets) do not support Google Sheets API. Copying the data into a sheet created directly in Google Sheets resolved the issue.

Solution 2:[2]

I've never seen a way in IAM to grant domain-wide delegation before.

Typically the developer ID is whitelisted in the domain CPanel like described in these docs.

(The paragraph that says "Then an administrator of the Google Apps domain must complete the following steps".)

Solution 3:[3]

Specify the user that you want to get messages for. In your case, it'd look like this:

credential = GoogleCredential
                .FromStream(stream)
                .CreateScoped(new[]{ GmailService.Scope.GmailModify })**
                .CreateWithUser("me") **;

Solution 4:[4]

I used Service Account and I did not authorize my service/application to access user data on behalf of users in my case when I saw the same error. If it is your case, see

a) Delegating domain-wide authority to the service account if you use the private domain and have Google admin access.

b) Generate and store refresh token to access the user's account (through access token).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Colin Zabransky
Solution 2 Uwe Keim
Solution 3 Ritesh Sinha
Solution 4