Search code examples
c#google-oauthgmail-apigoogle-workspaceservice-accounts

gmail API deleting eMails using service account


I am trying to read and delete my mails for some Automated tests, my problem is I cant use oauth because it requiers user input. So I was trying to use an service account

But when I ran my code I got this an Error

Now im wondering if there is anything wrong with my code or with my permissions in the Google console

Error:

'One or more errors occurred. (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:"")'

Occured here: credential.RequestAccessTokenAsync(CancellationToken.None).Result

Code

        private ServiceAccountCredential credential;
        private GmailService Service { get; set; }

        // If modifying these scopes, delete your previously saved credentials
        private static string[] Scopes = { GmailService.Scope.MailGoogleCom };
        private static string applicationName = "EmailReader";
        private static string credentialsFile = "emailreader-289206-c91027110691.p12";
        private static string keyPassword = "notasecret";
        private static string serviceAccountEmail = "auristesterdienstkonto@emailreader-289206.iam.gserviceaccount.com";
        private static string userEmail = "[email protected]";

        private Func<Message, bool> lastFilter;

        public GmailLibary() //my constructor
        {
            var certificate = new X509Certificate2(
                credentialsFile,
                keyPassword,
                X509KeyStorageFlags.Exportable);

            credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    User = userEmail,
                    Scopes = Scopes
                }.FromCertificate(certificate)
            );

            if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            {
                Service = new GmailService(
                    new BaseClientService.Initializer()
                    {
                        ApplicationName = applicationName,
                        HttpClientInitializer = credential
                    }
                );
            }
        }

Permissions enter image description here enter image description here


Solution

  • "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."

    Normally means that you are using the code for a service account, but you have not created service account credentials on Google cloud console. Make sure that the service account you have set up also appears on google cloud console I'm not sure that the service account created over on Google cloud platform is the same thing. (not that i have tested it.)

    In the case of Gmail API it is also the result of you not having properly set up domain wide delegation in your google workspace account. Remember that service accounts only work with the gmail api with one of your domain emails you cant use it with a standard gmail email.