如何硬编码 google 驱动器 api 的身份验证和授权部分?

How can I hardcode the authentication and authorization part of google drive api?

目前我有用户授权的代码,然后他们可以使用 OAuth2 访问他们自己的 Google Drives 帐户中的文件,但是现在我想对身份验证部分进行硬编码aspx.cs 页面 的源代码中的授权部分。

可能吗?我目前使用的语言是 ASPxC#。我将此 using ASPSnippets.GoogleAPI; 用于以下代码。

这是我的 0Auth2 使用客户端密码和客户端 ID 的代码

protected void Page_Load(object sender, EventArgs e)
{
    GoogleConnect.ClientId = "client_id";
    GoogleConnect.ClientSecret = "client_secret";
    GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
    GoogleConnect.API = EnumAPI.Drive;
    if (!string.IsNullOrEmpty(Request.QueryString["code"]))
    {
        string code = Request.QueryString["code"];
        string json = GoogleConnect.Fetch("me", code);
        GoogleDriveFiles files = new JavaScriptSerializer().Deserialize<GoogleDriveFiles>(json);

        //Remove the deleted files.
        dlFiles.DataSource = files.Items.Where(i => i.Labels.Trashed == false);
        dlFiles.DataBind();
    }
    else if (Request.QueryString["error"] == "access_denied")
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
    }
    else
    {
        GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.readonly");
    }
}

Tl;Dr 没有办法"hardcode the authentication part"

您似乎试图绕过您的用户在 Google 服务器上输入用户名和密码。你不能这样做。 OAuth 明确设计用于防止用户必须与您的站点共享他们的 Google 凭据:

Using OAuth 2.0 to Access Google APIs

请注意,在上面,用户将他们的 "User login & Consent" 输入到 Google 服务器 ,而不是您的服务器。您所看到的只是令牌响应。这将为您提供 window 访问该用户信息的权限,但随后会过期,需要您获取新的令牌。因此,您永远看不到任何可以有用地硬编码的信息。

系统明确设计为防止您硬编码(ing [sic])身份验证部分

如果您不想提示用户同意,您唯一的选择是使用 Service Account。话虽如此,在我看来,Google Drive.

似乎不支持(可以理解)这个

This question 涵盖了访问您的 自己的驱动器 以及如何实现这一点。但是您不能这样做来访问其他人的驱动器。

我不确定您想对哪个代码进行硬编码。

  1. 访问令牌(仅适用一个小时,不值得硬编码)
  2. 刷新令牌(长寿命可以硬编码,但不是一个好主意,见下文)
  3. 客户端 ID(是的,您可以对其进行硬编码。)
  4. 客户端机密(是的,您可以对其进行硬编码)

它的工作方式是您请求用户的访问权限并获得刷新令牌,您应该存储这些刷新令牌。如果用户想再次登录或者您需要再次访问他们的数据,您可以使用刷新令牌请求一个新的访问令牌,并且他们可以访问用户数据。

假设您有这些刷新令牌的列表,您可以在您的应用程序中对它们进行硬编码以供以后使用。然而,这是一个坏主意。刷新令牌可能会过期。

  1. 用户可以删除您的访问权限
  2. 六个月未使用的刷新令牌将自动过期
  3. 如果用户请求了超过 50 个刷新令牌,旧的将停止工作
  4. 随机 Google 个错误

因此,如果需要,您的应用程序最好能够再次请求用户访问。

这是使用 google .net 客户端库进行身份验证的代码,它存储用户凭据。如果用户没有有效的刷新令牌,那么它将提示用户再次访问。

private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
    {
        try
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(clientSecretJson))
                throw new ArgumentNullException("clientSecretJson");
            if (!File.Exists(clientSecretJson))
                throw new Exception("clientSecretJson file does not exist.");

            // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
            using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                // Requesting Authentication or loading previously stored authentication for userName
                var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                         scopes,
                                                                         userName,
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;

                credential.GetAccessTokenForRequestAsync();
                return credential;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Get user credentials failed.", ex);
        }
    }

存储这些凭据后,您将不需要再次提示用户进行访问。

注意:仅当您作为开发人员想要在您控制的 google 驱动器帐户上共享信息时,才应使用 IMO 服务帐户。不应使用服务帐户访问私人用户数据。这就是 Oauth2 的用途。

注意 2:尽管您可以考虑将其放入配置文件中,但您可以对客户端 ID 和密码进行硬编码。或者像上面的例子一样使用客户端密码 json。

代码从我的 sample project

中窃取

服务帐户 VS Oauth2

如果文件在用户 Google Drive 帐户上,那么您需要访问权限。您将不得不向他们请求访问权限,这是没有办法解决的,而且它与客户端库无关,这就是 Oauth 的工作方式。如果您试图访问用户拥有的私人数据,您需要获得他们的许可。

如果您尝试访问您个人控制的 Google Drive 帐户并希望授予所述用户访问该帐户上的文件的权限,那么您应该使用服务帐户。您可以通过获取服务帐户电子邮件地址并与其共享目录来授予服务帐户访问您的 google 驱动器帐户的权限。然后服务帐户将有权访问该目录。我的另一个教程在这里 Google Drive with service accounts

您可能会发现我的系列教程很有用Google Development for beginners this part is on service accounts Google Developer service accounts