oAuth2.0 for google drive C#WPF

时间:2014-09-05 05:05:25

标签: c# wpf google-drive-api

每次我连接到谷歌驱动器时,它都会抛出WebException 401 Unauthorized。

   WebClient wC = new WebClient();
   var down = wC.DownloadString("https://www.googleapis.com/drive/v2/about?includeSubscribed=true&key=[api-key]");
   JObject o = JObject.Parse(down);

   Console.WriteLine("Name, " +o["name"]);
   Console.ReadLine();

我想创建C#桌面应用程序。

2 个答案:

答案 0 :(得分:0)

您应该使用您的网络请求发送身份验证标头。我有自己的开源轻量级库,可以简化Google Drive上的文件处理:https://github.com/AlexeyVlg/Pranas.Net.Clouds您不需要使用它,但在此库中,您可以找到有关如何使用RestSharp库获取授权令牌的示例: https://github.com/AlexeyVlg/Pranas.Net.Clouds/blob/master/Pranas.Client.GoogleDrive/Business/Auth/DriveAuthorization.cs。只需下载C#WPF示例并试用即可。 请记住在DriveAuthData类中指定AppClientId,AppClientSecret和AppClientRedirectUri以使用此示例。 您可以在https://developers.google.com/drive/web/about-auth了解有关授权的更多信息。

答案 1 :(得分:0)

您可以使用此代码

   UserCredential credential;
        try
        {                
            using (var stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "client_secrets.json"), FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive },
                    acocuntAddress, CancellationToken.None, new FileDataStore("Drive.Auth.Store")).Result;

            }               
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "OutlookPlugin",
            });               
            //give list of files
                var items = service.Files.List().Execute().Items;