Step 1: Create a Service Account (Google Cloud)
Project Selection: Log in to the Google Cloud Console and select your project.
Enable APIs: Go to APIs & Services > Library, search for required APIs (e.g., Admin SDK API, Gmail API), and click Enable.
Create Account: Navigate to IAM & Admin > Service Accounts and click + Create Service Account.
Identity: Enter a name and ID, then click Create and Continue.
Skip Project Roles: Skip optional role assignments, as DwD permissions are managed in the Workspace Admin Console, not via IAM. Click Done.
Step 2: Download Credentials and Copy Client ID
Generate Key: Select your service account, go to the Keys tab, click Add Key > Create new key, choose JSON, and save the downloaded file securely.
Copy Client ID: On the Details tab, locate and copy the Unique ID (also called Client ID), which is a 21-digit numeric string.
Step 3: Authorize Domain-Wide Delegation (Google Admin)
Open Admin Console: Sign in to the Google Admin Console as a Super Administrator.
Navigate to API Controls: Go to Menu > Security > Access and data control > API controls.
Manage Delegation: Click Manage Domain Wide Delegation, then click Add new.
Authorize Scopes: * Client ID: Paste the numeric 21-digit ID copied in Step 2.
OAuth Scopes: Enter a comma-separated list of required scopes (e.g., https://www.googleapis.com/auth/gmail.settings.sharing).
Save: Click Authorize to finalize.
Place the file in the same location as the compiled binary.
Execute in package manager console Install-Package Google.apis.gmail.v1
and Install-Package Google.apis.auth
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
Imports System Imports System.IO Imports System.Threading Imports Google.Apis.Auth.OAuth2 Imports Google.Apis.Gmail.v1 Imports Google.Apis.Gmail.v1.Data Imports Google.Apis.Services Imports Google.Apis.Util.Store Imports Newtonsoft.Json.Linq 'Create a service account, add the clientid to the domainwide access. This access takes 15 or more minutes to propagate access through the system 'Create a JSON key Public Class GmailDelegationManager Public Shared Sub GrantAccess(jsonKeyPath As String, delegatorEmail As String, delegateEmail As String) Try ' 1. Load the raw JSON from your key file Dim jsonText As String = File.ReadAllText(jsonKeyPath) Dim keyData = JObject.Parse(jsonText) ' 2. Extract the necessary fields manually Dim serviceAccountEmail As String = keyData("client_email").ToString() Dim privateKey As String = keyData("private_key").ToString() ' 3. Configure the Initializer properly Dim initializer As New ServiceAccountCredential.Initializer(serviceAccountEmail) With { .User = delegatorEmail, .Scopes = {GmailService.Scope.GmailSettingsSharing} } ' This is where the private key is correctly applied initializer.FromPrivateKey(privateKey) ' 4. Create the final credential object Dim credential As New ServiceAccountCredential(initializer) ' 5. Initialize the Gmail Service Dim service As New GmailService(New BaseClientService.Initializer() With { .HttpClientInitializer = credential, .ApplicationName = "Gmail Delegation Tool" }) ' Create the Delegate object (remember the square brackets for VB.NET) Dim newDelegate As New Google.Apis.Gmail.v1.Data.[Delegate]() With { .DelegateEmail = delegateEmail } ' Execute the request to create the delegation ' "me" refers to David because the service is impersonating him Dim request = service.Users.Settings.Delegates.Create(newDelegate, "me") Dim result = request.Execute() Console.WriteLine($"Success! {result.DelegateEmail} can now access {delegatorEmail}'s mail.") Console.WriteLine($"Status: {result.VerificationStatus}") ' Usually returns 'accepted' Catch ex As Google.Apis.Auth.OAuth2.Responses.TokenResponseException Console.WriteLine("Auth Error: Ensure Domain-Wide Delegation is active for this Client ID.") Catch ex As Exception Console.WriteLine("Error: " & ex.Message) End Try End Sub Public Shared Sub RemoveEmailDelegation(jsonKeyPath As String, delegatorEmail As String, delegateEmail As String) Try ' 1. Load the Service Account JSON and configure impersonation Debug.WriteLine("Loading credentials for revocation...") Dim jsonText As String = File.ReadAllText(jsonKeyPath) Dim keyData = JObject.Parse(jsonText) Dim serviceAccountEmail As String = keyData("client_email").ToString() Dim privateKey As String = keyData("private_key").ToString() ' David (delegatorEmail) is the one we impersonate to remove the delegate Dim initializer As New ServiceAccountCredential.Initializer(serviceAccountEmail) With { .User = delegatorEmail, .Scopes = {GmailService.Scope.GmailSettingsSharing} } initializer.FromPrivateKey(privateKey) Dim credential As New ServiceAccountCredential(initializer) ' 2. Initialize the Gmail Service Using service As New GmailService(New BaseClientService.Initializer() With { .HttpClientInitializer = credential, .ApplicationName = "Gmail Delegation Tool" }) Debug.WriteLine($"Attempting to remove delegate {delegateEmail} from {delegatorEmail}...") ' 3. Execute the Delete request ' userId "me" refers to the impersonated delegator (David) ' delegateEmail is Becky's primary email address Dim request = service.Users.Settings.Delegates.Delete("me", delegateEmail) request.Execute() Debug.WriteLine($"SUCCESS: Delegation revoked. {delegateEmail} no longer has access to {delegatorEmail}'s mail.") End Using Catch ex As Google.GoogleApiException When ex.Error.Code = 404 Debug.WriteLine("INFO: This delegate relationship does not exist or was already removed.") Catch ex As Exception Debug.WriteLine($"ERROR: Failed to revoke access. {ex.Message}") Throw End Try End Sub End Class |