Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

gmail-api

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 !

like image 974
Melvin Avatar asked Mar 14 '17 11:03

Melvin


People also ask

How do I refresh Gmail API token?

In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline"); ) and you will get it.

What is access token in API?

What is an Access Token? A credential that can be used by an application to access an API. Access Tokens can be either an opaque string or a JSON Web Token (JWT) . They inform the API that the bearer of the token has been authorized: to access a particular service or services.


1 Answers

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

like image 76
DaImTo Avatar answered Oct 17 '22 01:10

DaImTo