1

私はGoogle.Apis.Drive.v3をC#で使用しています。 このコードでは、ユーザーのドライブへのアクセスをリクエストしています。GoogleドライブのAPI、既に認証済みかどうかを知る方法

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"ファイルの存在をテストしていますか?

答えて

1

私の知る限り、あなたのコードが正常に実行され、結果が得られれば、承認は成功しています。

GoogleWebAuthorizationBroker.AuthorizeAsync(...).Result;

プロンプトが表示されたら、ユーザは、Webページ上のいずれかの許可または拒否ボタンをクリックしていない場合は、上記の、無期限に待機します。 try-catchブロックで例外をキャッチすることは、拒否やその他の予期しないエラー(Google Webサイトへの接続の失敗など)を処理する通常の方法です。より高度な方法でAuthorizeAsyncを処理する必要がある場合は、コードで「非同期タスク」構造体を使用することを検討してください。参照:https://www.infoq.com/articles/Tasks-Async-Await


は「.credentials /ドライブインhourcounter.jsonの」ファイルの存在をテストアクセスは、ローカルファイルを削除せずにhttps://security.google.com/settings/security/permissionsで、ユーザーによって取り消されることができて、間違いなく良い方法ではありません。

+0

GoogleWebAuthorizationBroker.AuthorizeAsync(に存在しているかどうかをチェックするためには)アクセスがユーザーによって取り消された場合にも渡されますが、サービスのAPIを呼び出すときに例外がスローされます – KevinBui

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

ユーザーがAllows it in the consent screenの場合、アプリの認可が得られます。

  1. ユーザーが承認すると、Googleはアプリケーションに短期間のアクセストークンを与えます。
  2. アプリケーションは、アクセストークンを要求に添付してユーザーデータを要求します。
  3. Googleがリクエストとトークンが有効であると判断した場合、リクエストされたデータを返します。

Googleがあなたのscopeに関して、要求されたデータを返す場合、それはあなたが許可されることを意味します。 ただし、Error 403 messageが届いた場合は、あなたに権限がないことを意味します。

0

資格がローカル

await new FileDataStore(credPath, true).GetAsync<TokenResponse>(userId) != null 
関連する問題