GDrive Impersonation with Powershell

56 Views Asked by At

I am trying to modify an existing powershell script which connects to a Google Drive by reading a .json file containing the service account credentials, private key, token uri, etc. This part works fine, but now I am trying to add a step where it impersonates another service account. The new svc account has already been given the appropriate G-suite/GDrive access. However, when I run the script I get the error "Error:"{ "error": { "code": 404, "message": "Not found; Gaia id not found for email [email protected]" Any assistance would be greatly appreciated.

function Get-GoogleDriveService
{
    Param (
        [Parameter(Mandatory=$true)]
        [string] $json_file,
        [Parameter(Mandatory=$false)]
        [string[]] $scopes = @(
            "https://www.googleapis.com/auth/drive.metadata.readonly",
            "https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive.appdata",
            "https://www.googleapis.com/auth/iam")
    )

    # Get service account credential from JSON file
    $gcred = [Google.Apis.auth.Oauth2.GoogleCredential]::FromFile($json_file)


    # Add scopes to credential
    $gcred_scoped = $gcred.CreateScoped($scopes)

    
    # get the user name from the Json file where it is called client_email
    $json = Get-Content $json_file
    $jcontainer = [Newtonsoft.Json.JsonConvert]::DeserializeObject($json)
    $client_email = $jcontainer["client_email"].Value


    # Add user to credential
    $gcred_user = $gcred_scoped.CreateWithUser($client_email)
    #$gcred_user = $gcred.CreateWithUser($client_email)
    
    # Add impersonation for deletes
    $impersonation_initializer= New-Object Google.Apis.auth.Oauth2.ImpersonatedCredential+Initializer("[email protected]")
    
    $gcred_impersonate = $gcred_user.Impersonate($impersonation_initializer)

    # Create Google Drive service
    $initializer = New-Object Google.Apis.Services.BaseClientService+Initializer
    $initializer.HttpClientInitializer = $gcred_impersonate
    $service = New-Object Google.Apis.Drive.v3.DriveService -argumentList $initializer

    return $service
        
}
0

There are 0 best solutions below