Google Drive SDK создает файл для пользователя

Здравствуйте

В настоящее время я пытаюсь создать файл под определенной учетной записью пользователя.
Учетная запись пользователя находится в моем домене Google.
Для Oauth я использую учетную запись службы.

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;
    }

Создание файла

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;
    }

Итак, здесь я создаю файл, так как я прошел аутентификацию с помощью ServiceAccount, вот куда загружается файл.

Вопрос

Мне нужно иметь возможность создавать/копировать этот файл для определенного пользователя в моем домене. И сделайте этого пользователя владельцем файла.

Приветствуется любая помощь.

Ссылка на старый пост

Передача владения с помощью Google SDK


person Nick Prozee    schedule 07.08.2014    source источник


Ответы (2)


Я пойду с Марселем Балком.

Таким образом, мы будем использовать олицетворение!

мы можем использовать учетную запись службы для аутентификации, затем использовать любую учетную запись электронной почты в нашем домене и загружать файлы. Загруженные файлы будут видны на Диске пользователей в разделе Мои файлы (мне не предоставлен доступ!). Файлы также принадлежат олицетворенной учетной записи. Протестировано в небольшом консольном приложении:

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******[email protected]";
        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();

        }
    }
}
person Wouter Spaans    schedule 12.08.2014

Вы можете легко сделать это, добавив пользователя в код. Смотрите пользователя, которого я добавил.

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="[email protected]" //Add this to your code!
       }.FromCertificate(certificate));

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

    return service;
}

Затем перейдите на admin.google.com --> Безопасность --> Дополнительные настройки --> Управление доступом клиента oauth.

Добавьте идентификатор клиента к имени клиента и укажите область действия (http://www.googleapis.com/auth/drive) в поле "Одна или несколько областей API"

person Marcel Balk    schedule 12.08.2014
comment
Это не работает, вы хотите аутентифицировать учетную запись службы при входе в учетную запись пользователя. - person Nick Prozee; 12.08.2014