Google 驱动器 api,如何知道是否已经通过身份验证?

Google Drive api, how to know if already authenticated?

所以我在 C# 上使用 Google.Apis.Drive.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”文件的存在??

据我了解,如果你的代码执行成功通过下面,得到一个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 撤销访问权限而不删除本地文件。

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

如果用户没有访问权限,那么 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);
 }
}

如果用户Allows it in the consent screen,您的应用获得授权。

  1. If the user approves, then Google gives your application a short-lived access token.
  2. Your application requests user data, attaching the access token to the request.
  3. If Google determines that your request and the token are valid, it returns the requested data.

如果 Google returns 请求的数据,相对于您的 scope,则表示您已获得授权。 但是,如果您得到 Error 403 message,则表示您没有权限。

检查本地是否存在凭据

await new FileDataStore(credPath, true).GetAsync<TokenResponse>(userId) != null