I have a program that fetches e-mail from a google mailbox using IMAP. It currently uses username/password ("PLAIN") authentication in the IMAP protocol. I would like to change it to support XOAUTH2 authentication. The program is written in .NET and runs as a service on Windows and so there is no opportunity for the authorization consent request that one normally associates with OAuth2.
It seems to me that the proper procedure would be:
- Create a "Project" in Google on the e-mail address account for the sole purpose of fetching mail.
- Create a "Service Account" on that project (which I believe should give the ability to have unattended access)
- Upload a certificate so Google can use its public key to authenticate the Access Token request, which is signed using the private key by the client Windows service
- Use ServiceAccountCredential and its Initializer class (part of the Google.Apis.Auth NUGet package) to obtain an Access Token
- Pass the Access Token during the IMAP protocol setup.
I seem to have a choice of hitting two walls: The first, when I omitted setting the User when building the ServiceAccountCredential, I could obtain an Access Token but when used in IMAP I would get an authorization failure. The second, when I supplied the e-mail address as the User, I would get the following error trying to obtain the access token:
Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested
I am assuming here that the "client" mentioned in the error message refers to the Google Project, though I could be wrong, it could refer to the Service Account. In any case, the scope being requested is
In the setup for the Google Project I can see ("Enabled APIs and Services") where I can enable certain API's for the Project (GMail API is enabled).
I can also see, if I go to the "OAuth Consent Screen", where I can authorize specific scopes for the selected API and in particular where I can enable the https://mail.google.com/ scope. However, the whole goal here is to not have any consent screen (and in any case enabling the https://mail.google.com/ scope here doesn't help).
I don't want access to any other mailbox, so I don't think I need "Domain-Wide Delegation" on the Service Account. Besides, this is just an individual mail account, there is no Google Domain involved.
It seems that I'm missing how to authorize the scope for the Service Account (or the Project), although the "this OR that" nature of the error message may be misleading me. Or perhaps I'm completely misunderstood this...