2015-10-05 109 views
2

我花了很多時間嘗試獲取身份驗證令牌。從Google中的客戶端電子郵件和私鑰(服務帳戶)獲取令牌

我需要向我的用戶展示收集的一些Google Analytics信息(我是Google Analytics的所有者)。我創建了一個服務帳戶,我用這個例子測試了所有的東西,並且所有的工作都很好(當然使用Nuget包)。

例子:Link

代碼示例工作:

string[] scopes = new string[] {AnalyticsService.Scope.Analytics}; // view and manage your Google Analytics data 

var keyFilePath = @"c:\file.p12" ; // Downloaded from https://console.developers.google.com 
var serviceAccountEmail = "[email protected]"; // found https://console.developers.google.com 

//loading the Key file 
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); 
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { 
                Scopes = scopes}.FromCertificate(certificate)); 

我已經使用小提琴手,我可以看到令牌被谷歌和我的應用程序之間的「飛」,但我沒有任何選項採取它。

我需要做的,像Python的這段代碼,但在C#中使用Embed API

# service-account.py 

import json 
from oauth2client.client import SignedJwtAssertionCredentials 

# The scope for the OAuth2 request. 
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' 

# The location of the key file with the key data. 
KEY_FILEPATH = 'path/to/json-key.json' 

# Load the key file's private data. 
with open(KEY_FILEPATH) as key_file: 
    _key_data = json.load(key_file) 

# Construct a credentials objects from the key data and OAuth2 scope. 
_credentials = SignedJwtAssertionCredentials(
    _key_data['client_email'], _key_data['private_key'], SCOPE) 

# Defines a method to get an access token from the credentials object. 
# The access token is automatically refreshed if it has expired. 
def get_access_token(): 
    return _credentials.get_access_token().access_token 

如果您對嵌入API讀取文檔,您將看到您需要的令牌......

/** 
    * Authorize the user with an access token obtained server side. 
    */ 
    gapi.analytics.auth.authorize({ 
    'serverAuth': { 
     'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}' 
    } 
    }); 

以上所有信息...我如何獲得服務憑證?謝謝!!

回答

2

這對我的作品

C#代碼:

public string bearer; 
    GoogleCredential credential; 

     string fichero = Server.MapPath("") + "//file.json"; 
     using (Stream stream = new FileStream(fichero, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      credential = GoogleCredential.FromStream(stream); 
     } 
     credential = credential.CreateScoped(new[] { 
     "https://www.googleapis.com/auth/analytics.readonly" }); 


     try 
     { 
      Task<string> task = ((ITokenAccess)credential).GetAccessTokenForRequestAsync(); 
      task.Wait(); 
      bearer = task.Result; 

     } 
     catch (AggregateException ex) 
     { 
      throw ex.InnerException; 
     } 

Javascript代碼:

gapi.analytics.auth.authorize({ 
    'serverAuth': { 
     'access_token': '<%=bearer%>' 
    } 
}); 
+0

謝謝!我一直在尋找這樣的事情2個小時。 –

0

所以你們都很擅長創建ServiceAccountCredential。接下來你需要做的是在你的ServiceAccountCredential實例上調用RequestAccessTokenAsync()實例,之後該實例將使用訪問令牌填充Token屬性,例如

if (await credential.RequestAccessTokenAsync(new CancellationToken())) { 
    var token = credential.Token.AccessToken; 
} 

然後,您可以在您的JavaScript中使用該標記。

相關問題