我花了很多時間嘗試獲取身份驗證令牌。從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個小時。 –