需要通过 IIS 应用程序访问 Google Drive V3 - 不使用 MVC

Need to Access Google Drive V3 via IIS application - Without Using MVC

我的需求非常具体。我需要访问 Google 驱动器上的共享文件夹目录。其中唯一的东西是空的表格文档和电子表格模板。文件夹内没有任何有价值的东西,仅供内部使用。所以,我可以非常乐观地关注 WRT 的安全问题。我只需要访问权限。

我正在扩展作为 IIS 应用程序运行的现有 ERP 系统。 我的定制是扩展 ERP 的 .NET 类 的 .NET/C# 项目。我无法实施 login/auth 系统,因为 ERP 已经存在一个系统。

我做了 .NET 快速入门,但当然这是一个控制台应用程序,当我将它移至 IIS 时将无法使用。遵循标准 MVC 模型的建议对我不起作用——添加第二个网络 site/page 对我的需要来说是不必要的复杂。

我的问题是:如何授权访问 Google 驱动器

A) 在 IIS 中运行 B) 不需要单独的 ASP Web 应用程序来实现 MVC 进行授权。

===============================

类似于以下问题:

您可以在 asp.net 应用程序中使用 OAuth 授权:

使用 GetAuthorizationUrl() 创建 Web 服务器 client_secret.json.by 创建 url 以获取临时 token.Redirect 到 GoogleCallback() 并使用 ExchangeAuthorizationCode() 获取刷新和访问令牌。将它们保存到文件“~/Resources/driveApiCredentials/drive-credentials.json/Google.Apis.Auth.OAuth2.Responses.TokenResponse-{account}”。使用这个保存的令牌。

您可以参考以下link了解更多详情:

https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-aspnet-mvc

Google Drive API not uploading file from IIS

Jalpa 的回答不是我要找的,也没有在任何链接中引用任何内容。

我要把我的答案放在这里,因为它是我需要的,它可能对其他人有用。

首先概述

Google 的 .NET 快速入门仅显示基于控制台的解决方案。许多人已经发现,当您切换到基于 IIS 的解决方案时,这将不起作用。就好像 API 故意挫败了你这样做的企图。它根本不允许您使用为使用 GoogleWebAuthorizationBroker.AuthorizeAsync 的本地应用程序创建的令牌——它会出错 即使不需要浏览器 。 (即令牌尚未过期,因此不需要浏览器验证任何内容。)

尝试 运行 刷新授权会给您令牌,但不是服务。即使令牌有效,您仍然无法使用 AuthorizeAsync 从 IIS 应用程序获取服务(见上文)

我是这样处理的:

  1. 执行快速启动和运行弹出本地浏览器并允许您登录和验证的授权。
  2. 它创建一个本地文件夹(token.json),其中放置一个令牌文件(Google.Apis.Auth.OAuth2.Responses.TokenResponse-user) 它只是一个json 文件。在记事本++中打开它,你会发现字段:
  • "access_token": "token_type": "expires_in": "refresh_token":
    “范围”:“已发行”:“IssuedUtc”:

您需要 refresh_token。我只是将它与我​​从 Google API 控制台(即“credentials.json”)下载的初始凭据文件结合起来,并将其命名为“skeleton_key.json”

此文件是您永久生成有效令牌所需的全部内容。

我有 2 个 classes 用于此。首先是创建驱动服务的class:

public class GDriveClass
{
    public String LastErrorMessage { get; set; }
    static string[] Scopes = { DriveService.Scope.Drive }; // could pull this from skeleton_key
    static string ApplicationName = "GDrive Access"; // this is functionally irrelevant
    internal UserCredential usrCredentials;
    internal Google.Apis.Drive.v3.DriveService CurrentGDriveService = null;
    internal String basePath = ".";  // this comes in from calling program 
                                     // which uses HttpContext.Current.Server.MapPath("~");

    public GDriveClass(string logFileBasePath)
    {
        basePath = logFileBasePath;
        LastErrorMessage = "";
    }

    #region Google Drive Authenticate Code
    public bool AuthenticateUser(string FullTokenAccessFileName)
    {
        UserCredential credential;
        String JsonCredentialsonFile = System.IO.File.ReadAllText(FullTokenAccessFileName);
        string credPath = basePath + @"\Credentials\token.json";
        // Force a Refresh of the Token
        RefreshTokenClass RTC = new RefreshTokenClass();
        // Set field values in RefreshTokenClass:
        var jObject = Newtonsoft.Json.Linq.JObject.Parse(JsonCredentialsonFile);
        var fieldStrings = jObject.GetValue("installed").ToString();
        var fields = Newtonsoft.Json.Linq.JObject.Parse(fieldStrings);
        RTC.client_id = fields.GetValue("client_id").ToString();
        RTC.client_secret = fields.GetValue("client_secret").ToString();
        RTC.refresh_token = fields.GetValue("refresh_token").ToString();
        RTC.ExecuteRefresh();  // this gets us a valid token every time

        try
        {
            GoogleCredential gCredentials = GoogleCredential.FromAccessToken(RTC.access_token);
            CurrentGDriveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = gCredentials,
                ApplicationName = ApplicationName,
            });
            return true;
        }
        catch (Exception ex)
        {
            LastErrorMessage = "Error: Authenticating - " + ex.Message;
            return false;
        }
    }

用法非常简单:

            string TokenFile = @basePath + @"\skeleton_key.json";
            GDRIVER.AuthenticateUser(TokenFile);
            var rslt = GDRIVER.LastErrorMessage;
            if (!String.IsNullOrEmpty(rslt))
            {
                WriteToLogFile("ERROR in Google AuthenticateUser() ");
                AlertMessage("Unable To Connect to Google Drive - Authorization Failed");
                return;
            }

这是根据需要通过 REST API 刷新令牌的 class:

public class RefreshTokenClass
{
    public string application_name { get; set; }
    public string token_source { get; set; }
    public string client_id { get; set; }
    public string client_secret { get; set; }
    public string scope { get; set; }
    public string access_token { get; set; }
    public string refresh_token { get; set; }

    public RefreshTokenClass()
    {

    }

    public bool ExecuteRefresh()
    {
        try
        {
            RestClient restClient = new RestClient();
            RestRequest request = new RestRequest();
            request.AddQueryParameter("client_id", this.client_id);
            request.AddQueryParameter("client_secret", this.client_secret);
            request.AddQueryParameter("grant_type", "refresh_token");
            request.AddQueryParameter("refresh_token", this.refresh_token);
            restClient.BaseUrl = new System.Uri("https://oauth2.googleapis.com/token");
            var restResponse = restClient.Post(request);
            // Extracting output data from received response
            string response = restResponse.Content.ToLower();  // make sure case isn't an issue

            // Parsing JSON content into element-node JObject
            var jObject = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);

            //Extracting Node element using Getvalue method
            string _access_token = jObject.GetValue("access_token").ToString();
            this.access_token = _access_token;
            return true;
        }
        catch (Exception ex)
        {
            //Console.WriteLine("Error on Token Refresh" + ex.Message);
            return false;
        }

    }

注意:这利用了 Newtonsoft.Json 和 RestSharp。

感谢用户:“OL”。谁给了我从令牌创建服务的方法(不知何故我在文档中错过了!)

并致用户:“purshotam sah”以获得干净的 REST API 方法 Generate Access Token Using Refresh Token