2017-02-24 482 views
1

我創建了一個控制檯應用程序,該應用程序使用OAuth2對GoogleAnalyticsApiV4進行身份驗證以查詢一些數據。該應用程序按預期工作,但我們希望自動化該過程,以便應用程序可以安排爲每天運行一次。這裏的問題是應用程序將託管在Azure上,並且用戶無法接受第一次運行應用程序時在瀏覽器中彈出的Google驗證請求。使用OAuth2在C#中使用Google API進行身份驗證

按照網上的帖子和谷歌文檔,我目前的解決方案來驗證這是

 try 
     { 
      var credential = GetCredential().Result; 

      using (var svc = new AnalyticsReportingService(
      new BaseClientService.Initializer 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = "Google Analytics API Console" 
      })) 
     { 
      ///// Query some data///// 
     } 



static async Task<UserCredential> GetCredential() 
{ 
    using (var stream = new FileStream("client_secret.json", 
     FileMode.Open, FileAccess.Read)) 
    { 
     string loginEmailAddress = ConfigurationManager.AppSettings["GoogleUsername"]; 
     return await GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets, 
      new[] { AnalyticsReportingService.Scope.Analytics }, 
      loginEmailAddress, CancellationToken.None, 
      new FileDataStore("GoogleAnalyticsApiConsole")); 
    } 
} 

這個解決方案工作得很好,只要用戶可以輸入憑據與谷歌進行身份驗證並接受認證請求。不幸的是,只要應用程序移動到另一臺機器上,它需要重新進行身份驗證,並且用戶需要再次輸入憑據並接受請求。

我一直在尋找一種方式將用戶帶出進程,以便應用程序可以在azure上運行,但是沒有發現任何關於如何在c#中執行此操作的明確信息。

請有人能描述我如何在沒有用戶的情況下使用谷歌認證我的應用程序,或者指出我準確覆蓋過程的文檔方向。

幫助或例子將不勝感激。

回答

1

您有幾個選項。

這是您有權訪問的帳戶。如果是,那麼你可以使用服務帳戶。服務帳戶通過服務帳戶電子郵件地址進行預先授權,並在帳戶級別以Google Analytics(分析)管理員的用戶身份添加,並且服務帳戶只要有效即可訪問該帳戶。沒有彈出窗口是必需的。我對如何與服務進行身份驗證的一些示例代碼佔here

/// <summary> 
    /// Authenticating to Google using a Service account 
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount 
    /// </summary> 
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> 
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param> 
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns> 
    public static AnalyticsReportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath) 
    { 
     try 
     { 
      if (string.IsNullOrEmpty(serviceAccountCredentialFilePath)) 
       throw new Exception("Path to the service account credentials file is required."); 
      if (!File.Exists(serviceAccountCredentialFilePath)) 
       throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath); 
      if (string.IsNullOrEmpty(serviceAccountEmail)) 
       throw new Exception("ServiceAccountEmail is required."); 

      // 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[] { AnalyticsReportingService.Scope.Analytics };    // View your Google Analytics data 

      // For Json file 
      if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json") 
      { 
       GoogleCredential credential; 
       using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)) 
       { 
        credential = GoogleCredential.FromStream(stream) 
         .CreateScoped(scopes); 
       } 

       // Create the Analytics service. 
       return new AnalyticsReportingService(new BaseClientService.Initializer() 
       { 
        HttpClientInitializer = credential, 
        ApplicationName = "AnalyticsReporting Service account Authentication Sample", 
       }); 
      } 
      else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12") 
      { // If its a P12 file 

       var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); 
       var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) 
       { 
        Scopes = scopes 
       }.FromCertificate(certificate)); 

       // Create the AnalyticsReporting service. 
       return new AnalyticsReportingService(new BaseClientService.Initializer() 
       { 
        HttpClientInitializer = credential, 
        ApplicationName = "AnalyticsReporting Authentication Sample", 
       }); 
      } 
      else 
      { 
       throw new Exception("Unsupported Service accounts credentials."); 
      } 

     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Create service account AnalyticsReportingService failed" + ex.Message); 
      throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex); 
     } 
    } 

如果這不是你可以做的。然後你應該意識到事實:filedatastore()默認將你的憑證存儲在%appData%中,你可以簡單地將該文件與代碼一起復制到新的服務器上。

您也可以移動位置有些是其他然後%APPDATA%通過使用下面的代碼:

new FileDataStore(@"c:\datastore",true)  

我有filedatastore是如何工作的教程。這裏File datastore demystified

預授權服務帳戶到Google Analytics。 Google分析網站的管理員部分。授予它閱讀權限應該足夠。

enter image description here

+0

謝謝你的回覆迅速,我有機會獲得帳號,所以我現在看你的示例代碼。 – user2920648

+0

確保您在Google Analytics(分析)管理員中授予訪問權限時,您可以在帳戶級別執行此操作。如果你對樣品有任何問題,請告訴我。 – DaImTo

+0

我有一個輕微的問題,將我的文件路徑設置爲服務帳戶憑據的json文件。我將該文件的名稱更改爲Secret.json,這會影響任何內容嗎? 我不明白爲什麼一串「/Files/Secret.json」不會工作 – user2920648

相關問題