Google Drive api,如何知道是否已通过身份验证?

时间:2016-08-21 16:45:18

标签: c# authentication google-drive-api google-oauth google-api-dotnet-client

所以我在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"的存在。文件??

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

  
      
  1. 如果用户批准,那么Google会为您的应用提供一个短期访问令牌。
  2.   
  3. 您的应用程序请求用户数据,将访问令牌附加到请求。
  4.   
  5. 如果Google确定您的请求和令牌有效,则会返回请求的数据。
  6.   

如果Google针对您的scope返回所请求的数据,则表示您已获得授权。 但是,如果您获得Error 403 message,则表示您没有权限。

答案 2 :(得分:0)

据我了解,如果您的代码执行成功通过以下内容并获得结果,则授权已成功。

GoogleWebAuthorizationBroker.AuthorizeAsync(...).Result;

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

如果您需要以更高级的方式处理AuthorizeAsync,您可能需要考虑使用&#34;异步任务&#34;代码中的结构。请参阅:https://www.infoq.com/articles/Tasks-Async-Await

测试&#34; .credentials / drive-hourcounter.json&#34;的存在文件绝对不是一个好方法,因为用户可以在https://security.google.com/settings/security/permissions撤销访问而不删除本地文件。

相关问题