【问题标题】:How can I make a server to server authentication to Google Drive Api?如何对 Google Drive Api 进行服务器到服务器身份验证?
【发布时间】:2018-06-07 02:05:10
【问题描述】:

我正在尝试在 .Net Framework 中对 Google Drive Api 进行服务器到服务器身份验证。

我看到很多user authentication 的例子,但也有少数server to server

看到有这个Google Api library in C#,但是不知道怎么用。

有人可以帮我吗?

【问题讨论】:

    标签: c# asp.net-mvc authentication google-api


    【解决方案1】:

    这里是一个例子,在 .Net Framework 中使用 MVC 和 API Client LibraryGoogle Drive API v3

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Web.Mvc;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Services;
    using static Google.Apis.Drive.v3.DriveService;
    
    namespace TestApiGoogle.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult GoogleAuth()
            {
                FileStream fsSource = new FileStream
                    (@"Path\secret_info.json", FileMode.Open, FileAccess.Read);
    
                string[] Scopes = { Scope.Drive };
                string ApplicationName = "Your app name";
    
                GoogleCredential credential = GoogleCredential.FromStream(fsSource)
                    .CreateScoped(Scopes);
    
                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
    
                // Define parameters of request.
                FilesResource.ListRequest listRequest = service.Files.List();
                listRequest.PageSize = 10;
                listRequest.Fields = "nextPageToken, files(id, name)";
    
                // List files.
                IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                    .Files;
    
                if (files != null && files.Count > 0)
                {
                    foreach (var file in files)
                    {
                        Console.WriteLine("{0} ({1})", file.Name, file.Id);
                    }
                }
                else
                {
                    Console.WriteLine("No files found.");
                }
    
                var jsonObject = new
                {
                    files
                };
    
                return Json(jsonObject, JsonRequestBehavior.AllowGet);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2020-03-20
      • 2020-04-22
      • 1970-01-01
      • 2010-10-21
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多