【问题标题】:Google api authorization raises the browser谷歌api授权提升浏览器
【发布时间】:2014-12-17 15:39:29
【问题描述】:

我正在编写一个小型桌面应用程序,它将文件上传到谷歌驱动器。所以当我登录我的谷歌帐户时一切都很好,但是当我没有登录时,程序会在此页面“https://accounts.google.com/ServiceLogin”上启动浏览器。我正在使用此代码:

        ClientSecrets secret = new ClientSecrets();
        secret.ClientId = "my_client_id";
        secret.ClientSecret = "my_client_secret";
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secret, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;

        var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "TestUpload" });

        File body = new File();
        body.Title = "Title123";
        body.Description = "Decription123";
        body.MimeType = "image/png";

        byte[] arr = System.IO.File.ReadAllBytes(fileName);
        System.IO.MemoryStream stream = new System.IO.MemoryStream(arr);

        FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/png");
        request.Upload();

那么如何在不启动浏览器的情况下以编程方式进行授权?

【问题讨论】:

  • 你通常不能使用 OAuth,协议的全部意义在于你永远不需要将密码直接告诉想要对你进行身份验证的应用程序。通常,如果您最终解决了这个限制并且发现您的应用的 API 密钥将被撤销。
  • @ScottChamberlain 所以有没有办法不提升浏览器?

标签: c# google-drive-api


【解决方案1】:

您的大部分问题是您没有保存身份验证。您正在请求访问但不保存它。在以下示例中,fileDataStore 将身份验证信息存储在您电脑上的 %AppData% 文件中,这样下次您运行程序时将不需要身份验证,并且当时也不需要您登录 Google。

//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive,
                                 DriveService.Scope.DriveFile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = 
            GoogleWebAuthorizationBroker
                          .AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID
                                                            , ClientSecret = CLIENT_SECRET }
                                          ,scopes
                                          ,Environment.UserName
                                          ,CancellationToken.None
                                          ,new FileDataStore("Daimto.GoogleDrive.Auth.Store")
                                          ).Result;
DriveService service = new DriveService(new BaseClientService.Initializer()
 {
 HttpClientInitializer = credential,
 ApplicationName = "Drive API Sample",
 });

 public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {

            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Title = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File uploaded by Diamto Drive Sample";
                body.MimeType = GetMimeType(_uploadFile);
                body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

                // File's content.
                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
                    request.Upload();
                    return request.ResponseBody;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return null;
                }
            }
            else {
                Console.WriteLine("File does not exist: " + _uploadFile);
                return null;
            }           

        }

此代码摘自Google Drive C# upload 教程,如果您想了解有关它的作用和工作原理的更多信息,您可能需要检查一下。在 GitHub 上的 Google-Dotnet-Samples 项目中还有一个工作示例项目。本教程基于该示例项目。

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    相关资源
    最近更新 更多