Client is unauthorized to retrieve access tokens using this method Gmail API C#
Asked Answered
E

5

45

I am getting the following error when i tried to authorize gmail api using service account

"Client is unauthorized to retrieve access tokens using this method"

static async Task MainAsync()
    {

        sstageEntities db = new sstageEntities();
        //UserCredential credential;
        Dictionary<string, string> dictionary = new Dictionary<string, string>();    
String serviceAccountEmail =
"xxx.iam.gserviceaccount.com";

        var certificate = new X509Certificate2(
            AppDomain.CurrentDomain.BaseDirectory +
              "xxx-8c7a4169631a.p12",
            "notasecret",
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

        //string userEmail = "[email protected]";

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                User = "[email protected]",
                Scopes = new[] { "https://mail.google.com/" }
            }.FromCertificate(certificate)
        );


        // Create Gmail API service.
        var gmailService = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.

        var emailListRequest = gmailService.Users.Messages.List("[email protected]");
        emailListRequest.LabelIds = "INBOX";
        emailListRequest.IncludeSpamTrash = true;
        emailListRequest.Q = "from:[email protected] is:unread";



        //Get our emails
        var emailListResponse = await emailListRequest.ExecuteAsync();

I am using the p12 key which i got while creating service account.But when i run my console app the following error occurs.Any help would be really appreciated.

Thanks in advance !

Eurasian answered 14/3, 2017 at 11:22 Comment(4)
Did you add the service account to the gsuite? developers.google.com/identity/protocols/…Canner
So only the admin of the organization can do that ? i am just an employee ?Eurasian
Yes I would think this is something only the admin can do for you.Canner
Hey DamlmTo yes the admin has to give access now its all solved thanks a lotEurasian
C
46

The service account needs to be authorized or it cant access the emails for the domain.

"Client is unauthorized to retrieve access tokens using this method"

Means that you have not authorized it properly check Delegating domain-wide authority to the service account

Canner answered 14/3, 2017 at 12:1 Comment(19)
Can a normal user access the gmail API through the service account authentication?Brunella
Service accounts only work with GSuite because you have to be able to preauthorize the service account and grant it access to the users account. There is no way to preauthorize a normal user Gmail account. So no you cant use a service account with a normal users gmail account.Canner
Thanks for the clarification DalmTo.Brunella
I get the same error, I set up the correct authorization in G Suite for the service account to access sheets through " googleapis.com/auth/spreadsheets" but I still get the error, any ideas?Griggs
@FabianBosler make sure you have the admin of the gsuite account set it up developers.google.com/identity/protocols/…Canner
I am the admin :DGriggs
@DaImTo, I found that sometimes "Delegating domain-wide authority to the service account" take a longer time to take effect. Usually a few seconds, but it can be longer than 5 minutes. Why does this happen? Any suggestion for this problem? Thanks.Casuistry
probably something on Google end. I don't have access to gsuite so can't test it myselfCanner
Important clarification: "Delegating domain-wide authority to the service account" MUST be enabled before you add service account and its scopes on "Manage API client access" page in G Suite Admin. Otherwise it will fail and require re-adding.Magner
@DalmTo so how are you supposed to authenticate a normal gmail account if you don't have gsuite? I've been trying to get this to work for 2 days now...Seclusive
@Seclusive your not supposed to its not allowed. Normal gmail accounts dont support service accounts. You need to use oauth2 and authenticate your account once and use the refresh token to access it again.Canner
Facing the issue that:To change domain wide delegation, a product name for the OAuth consent screen must be configured. You can enter the product name below. On some platforms, the email address is shown with the developer information. To select a different email address, configure consent screen. How do I fix that problem, bug report? It's the purpose of the service account to do this access because I donot want to have a consent screen. I donot want to have any user interaction and rely on a chain of refreshed tokens thereafter.Carpi
@Carpi have you tried doing what it says and just updating it. Service accounts will not popup with a consent screen. Your just changing the name of the product.Canner
@DaImTo Yhea thank you!! It actually works when configuring the consent screen. Still it's basically broken UX. :DCarpi
@Carpi actually i think its more broken user experience vs explanation of the reason for this. 🙃Canner
@DaImTo Yhea, much improvement potential there on Googles' side IMO^^Carpi
Its a free service you get what you pay for 💲.Canner
Let us continue this discussion in chat.Carpi
@Magner -- This comment solved my issue. This was the only place I found anything calling out the ordering, and turning everything "off" and then back on again fixed it.Salade
S
3

FWIW, since I'm too new to comment, DalmTo and Shane's answers pointed me in the right direction for my problem, which was that new functionality that I had added to an existing script (PHP) needed authorization of additional scopes for the service account. In my case, I'm working with the GMail API.

Besides the path mentioned in the Google documentation page that Shane cited, you can also go to https://admin.google.com/ac/owl/domainwidedelegation, where you can manage domain-wide delegation in a slightly different interface (I actually prefer it). I got to that page via Security > API Permissions, then clicking on the notice about those settings moving to App Access Control, where there's a "Manage Domain Wide Delegation" link at the bottom.

Sontag answered 3/5, 2020 at 6:37 Comment(0)
C
2

In my case authorization was given to an old client id in https://admin.google.com/

After providing the scopes with correct client ID it started to work. (Use the guide link mentioned by DalmTo in above answer.

Cypsela answered 7/4, 2020 at 16:32 Comment(0)
C
2

I had the same issue and it took me a while to realise what I was missing. I had already set Domain-wide authority in the service account setting. However, I had not added the clientid and API scope (e.g https://www.googleapis.com/auth/gmail.send, or https://mail.google.com/) in the Domain security settings, as per the link and screenshot below.

https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority

Specifically, these steps: steps I was missing

Clyster answered 23/4, 2020 at 10:47 Comment(0)
J
1

In case it helps anyone, I found that I had to enable the https://mail.google.com scope on the Google Workspace domain-wide delegation page.

This despite the fact that I needed only these two scopes for my application:

  • https://www.googleapis.com/auth/gmail.send
  • https://www.googleapis.com/auth/gmail.compose

At first I added just those two (send and compose) to the Google Cloud > APIs & Services > OAuth consent screen > Edit App > Scopes page (https://console.cloud.google.com/apis/credentials/consent/edit?project=project-name) and to the Google Workspace domain-wide delegation page (https://admin.google.com/ac/owl/domainwidedelegation)

But I would still get the error message: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

The only solution was to enable the https://mail.google.com scope on the Google Workspace domain-wide delegation page. This is the furthest reaching scope which is concerning, but I was able to retain only the send and compose scopes in the actual API configuration.

Johnstone answered 10/1 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.