谷歌驱动器api,如何知道如果已经认证

本文关键字:如果 认证 何知道 驱动器 api 谷歌 | 更新日期: 2023-09-27 18:03:23

所以我使用google . api . drive。c# v3。在这段代码中,我请求访问用户的驱动器。

    UserCredential credential;
    try
    {
        using (var stream =
            new System.IO.FileStream ("client_secret.json", System.IO.FileMode.Open, System.IO.FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = System.IO.Path.Combine (credPath, ".credentials/drive-hourcounter.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync (
                GoogleClientSecrets.Load (stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore (credPath, true)).Result;
        }
    }

我的问题是,我怎么知道用户是否已经给了我访问权限?现在我一直在运行这段代码,如果没有抛出异常,那么我就知道我有访问权限。有没有更好的解决方案?也许是测试"。credentials/drive-hourcounter"是否存在。json"文件? ?

谷歌驱动器api,如何知道如果已经认证

您真的不需要知道用户是否已经授予您访问权限,客户端库正在为您处理所有这些。

如果用户没有访问权限,那么FileDatastore将弹出身份验证屏幕并要求他们访问。然后,FileDatastore将在您的机器上存储一个文件,其中包含应用程序下次访问所需的凭据,而无需询问它们。如果文件不存在,那么它知道需要提示访问。"user"用于区分多个用户。

我有一个教程,解释了FileDatastore是如何工作的,关于Google .net客户端库Google .net - FileDatastore demystified

这是我使用的方法。和你的略有不同,但差别不大。

/// <summary>
/// This method requests Authentcation from a user using Oauth2.  
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static DriveService AuthenticateOauth(string clientSecretJson, string userName) {
 try {
  if (string.IsNullOrEmpty(userName))
   throw new Exception("userName is required.");
  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
  string[] scopes = new string[] {
   DriveService.Scope.Drive
  }; // View and manage the files in your Google Drive
  UserCredential credential;
  using(var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read)) {
   string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
   credPath = Path.Combine(credPath, ".credentials/apiName");
   // Requesting Authentication or loading previously stored authentication for userName
   credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
    scopes,
    userName,
    CancellationToken.None,
    new FileDataStore(credPath, true)).Result;
  }
  // Create Drive API service.
  return new DriveService(new BaseClientService.Initializer() {
   HttpClientInitializer = credential,
    ApplicationName = string.Format("{0} Authentication", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name),
  });
 } catch (Exception ex) {
  Console.WriteLine(string.Format("AuthenticateOauth failed: {0}", ex.Message));
  throw new Exception("RequestAuthentcationFailed", ex);
 }
}

你的应用程序获得授权,如果用户允许它在同意屏幕。

  • 如果用户批准,那么Google给你的应用程序一个短期访问令牌。
  • 您的应用程序请求用户数据,并将访问令牌附加到请求。
  • 如果Google确定您的请求和令牌是有效的,它返回请求的数据。
  • 如果Google返回请求的数据,就您的作用域而言,那么这意味着您被授权了。但是,如果您得到一个Error 403消息,这意味着您没有权限。

    据我所知,如果您的代码执行成功地通过下面并获得Result,则授权已成功。

    GoogleWebAuthorizationBroker.AuthorizeAsync(...).Result;

    如果用户没有在提示时单击网页上的允许或拒绝按钮,则上述将无限期等待。使用try-catch块捕获异常是处理拒绝和其他意外错误(例如无法连接到Google网站)的常用方法

    如果您需要以更高级的方式处理AuthorizeAsync,您可能需要考虑在代码中使用"async Task"结构。参见:https://www.infoq.com/articles/Tasks-Async-Await


    测试"。credentials/drive-hourcounter"是否存在。Json "文件绝对不是一个好方法,因为用户可以在https://security.google.com/settings/security/permissions上撤销访问,而无需删除本地文件。

    检查本地

    是否存在凭据
    await new FileDataStore(credPath, true).GetAsync<TokenResponse>(userId) != null