如何使服务器对Google云端硬盘Api进行服务器身份验证?

问题描述:

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

I'm trying to make a server to server authentication to Google Drive Api in .Net Framework.

我看到了许多使用用户身份验证的示例,但是有一些服务器到服务器.

I saw many examples with user authentication, but a few server to server.

我看到有一个 C#中的Google Api库,但是我不知道怎么用

I saw that there is this Google Api library in C#, but I don't know how to use it.

有人可以帮助我吗?

下面是一个示例,在.Net Framework中将MVC与 Google云端硬盘API v3

Here is an example, using MVC in .Net Framework with API Client Library and Google 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);
        }
    }
}