'Gmail API stopped working suddenly error mesage says unauthorized_client

We have been using Gmail API since the last 4 years without issue to read emails, but it suddenly stopped working and throwing exceptions: Error: "unauthorized_client", Description: "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:"

Checked the service account and it's active, so no issue there as well.

Thanks in advance.



Solution 1:[1]

Error: "unauthorized_client", Description: "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:"

Is a fairly common error, why you are first getting it now im not sure.

There are three different types of credentials for google Ouath that can be used with .net. Desktop app, installed app and service account.

The credentials are different for each one. The code that uses them is also different.

The error message you are getting says that you are using credentials with code that it is not designed for.

So if you are using a service account, make sure that

  1. the code you are using is for a service account.
  2. That you have domain wide delegation configured with your google workspace account.
  3. Make sure nothing was changed in the workspace configuration.

service account

Your code should look something like this.

        string ApplicationName = "Gmail API .NET Quickstart";
        const string serviceAccount = "[email protected]";

        var certificate = new X509Certificate2(@"D:\xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);

        var gsuiteUser = "[email protected]";

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

        }.FromCertificate(certificate);

        var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
        if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            throw new InvalidOperationException("Access token failed.");

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

Gmail api with google workspace and .net

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 DaImTo