How can I make a server to server authentication to Google Drive Api?

蹲街弑〆低调 提交于 2019-12-25 00:25:13

问题


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.

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

Can someone help me?


回答1:


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


来源:https://stackoverflow.com/questions/50731995/how-can-i-make-a-server-to-server-authentication-to-google-drive-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!