I have a Google Workspace with a few users in the directory, including a couple of Super Admins and regular users. I have set up a service account, created an API Client with Domain-wide Delegation.
In code, I have the following for setting up the credential:
GoogleCredential credential = GoogleCredential
.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "my-project-112233445566.json"))
.CreateScoped("https://mail.google.com/")
.CreateWithUser("[email protected]");
Note that the email address in CreateWithUser is a regular user in the directory. I have NOT set up Gmail Delegation for any users. I enabled Email Delegation in the Admin Console, but the section in the users Gmail Settings page has not appeared that would allow me to add a delegate. That shouldn't matter since I have done the Domain-wide Delegation, right?
After creating that credential above and trying to send a mail message, I receive the following error message:
The service gmail has thrown an exception. HttpStatusCode is Forbidden. Delegation denied for [email protected]
In addition to Domain-wide Delegation do I need to explicitly delegate authority to the service account on a per-user basis? According to the documentation I don't.
If I DO need explicit email delegation, why have I not seen the "Grant access to your account" section on the Accounts page of the Gmail Settings?
Service Account Setup
Google Cloud => IAM & Admin => Service Accounts setting page
Google Workspace => Security => API Controls => Domain-wide Delegation
Is there something else that I need to do to make impersonation happen?
CodePudding user response:
If you want the service account to impersonate a user on your domain then it has to be granted permission by the admin to impersonate that user.
The impersonation then also needs to be set up in your code.
var gsuiteUser = "[email protected]";
var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
{
User = gsuiteUser,
Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }
}.FromCertificate(certificate);
CodePudding user response:
I'm posting the answer here for visibility since it was resolved in the chat
It seems that the issue was not in the impersonation but by changing the userId="me"
.
We also created a new project, services account, key, and domain-wide delegation following the steps in the Google Documentation here.