Google Drive SDK creates file for user

Hello,
I am currently trying to create a file under a specific user account.
The user account is on my google domain.
For Oauth im using a service account.

DriveService ()

private static DriveService Service()
    {
        var certificate = new X509Certificate2(Constants.P12, "notasecret", X509KeyStorageFlags.Exportable);
        var credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(Constants.ServiceAccountEmail)
           {
               Scopes = new[] {
                   DriveService.Scope.Drive,
               }
           }.FromCertificate(certificate));

        // Create the service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "MyApplicationName",
        });

        return service;
    }

      

File creation

private static void CreateDriveDocument(string title)
    {
        Console.WriteLine("Google - Create New Document:" + Environment.NewLine);
        File body = new File();
        body.Title = title;
        body.Description = "A test document";
        body.MimeType = "text/plain";
        byte[] byteArray = System.IO.File.ReadAllBytes(@"C:\myDoc.txt");
        System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        //Callin the service at "Service()"
        FilesResource.InsertMediaUpload request = Service().Files.Insert(body, stream, "text/plain");
        request.Upload();
        File file = request.ResponseBody;
    }

      

So here I am creating a file since I am authenticated with ServiceAccount where the file is loaded.

Question

I need to be able to create / copy this file to a specific user using my domain. And make this user the owner of the file.

All help is greatly appreciated. Old post Link

TransferOwnership with Google SDK

+3


source to share


2 answers


I'll go with Marcel Balck.

This way we'll use impersonation!



we can use a service account to authenticate, then use any email account in our domain and upload files. The downloaded files will show up in the Drives section under My Files (not with me)! The files also belong to an impersonated account. Tested in a small console app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;

namespace UseWebServiceMethod
{
    class Program
    {
        // Goto https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients
        // Login met admin account => ****@***.***
        // Add/edit Client Name (Use Client ID of service account here) => 2***8.apps.googleusercontent.com
        // One or More API Scopes => https://www.googleapis.com/auth/drive 

        public const string ImpersonatedAccountEmail = "****@***.***";
        public const string ServiceAccountEmail      = "2******8@developer.gserviceaccount.com";
        public const string Key                      = @"C:\Users\Wouter\Desktop\GoogleTester\GoogleTester\A****c.p12";
        public const string FileToUpload             = @"C:\Users\Wouter\Desktop\GoogleTester\GoogleTester\whakingly.txt";
        public const string ApplicationName          = "A***l";

        static void Main()
        {
            var certificate = new X509Certificate2(Key, "notasecret", X509KeyStorageFlags.Exportable);
            var initializer = new ServiceAccountCredential.Initializer(ServiceAccountEmail)
            {
                Scopes = new[] { DriveService.Scope.Drive },
                User = ImpersonatedAccountEmail
            };

            var credential = new ServiceAccountCredential(initializer.FromCertificate(certificate));
            var driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            });

            // Show all files
            var list = driveService.Files.List().Execute();
            if (list.Items != null)
                foreach (var fileItem in list.Items)
                {
                    Console.WriteLine(fileItem.Title + " - " + fileItem.Description);
                }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();

            // Upload a new file
            File body = new File();
            body.Title = "whakingly.txt";
            body.Description = "A whakingly (that a new word I created just there) file thats uploaded with impersonation";
            body.MimeType = "text/plain";
            byte[] byteArray = System.IO.File.ReadAllBytes(FileToUpload);
            var stream = new System.IO.MemoryStream(byteArray);
            FilesResource.InsertMediaUpload request = driveService.Files.Insert(body, stream, "text/plain");
            request.Upload();
            File file = request.ResponseBody;
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();

            // Show all files
            var list2 = driveService.Files.List().Execute();
            if (list2.Items != null)
                foreach (var fileItem in list2.Items)
                {
                    Console.WriteLine(fileItem.Title + " - " + fileItem.Description);
                }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();

        }
    }
}

      

+3


source


You can easily do this by adding a user to your code. See the User I added.

private static DriveService Service()
{
    var certificate = new X509Certificate2(Constants.P12, "notasecret",X509KeyStorageFlags.Exportable);
    var credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(Constants.ServiceAccountEmail)
       {
           Scopes = new[] {DriveService.Scope.Drive},
           User="someuser@somedomain.someextension" //Add this to your code!
       }.FromCertificate(certificate));

    // Create the service.
    var service = new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "MyApplicationName",
    });

    return service;
}

      



Then go to admin.google.com -> Security -> Pre-access settings -> Manage oauth client access

Add customer ID to customer name and add scope ( http://www.googleapis.com/auth/drive ) in One or more API fields

+1


source







All Articles