获得令牌从客户的电子邮件和私钥(服务帐户)在谷歌



我花了很多时间试图获得一个验证令牌。

我需要向我的用户展示一些收集的分析信息(我是分析的所有者)。我已经创建了一个服务帐户,并且我已经用这个例子测试了所有这些,并且一切正常(当然,使用Nuget包)。

例子:联系

代码示例:

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 = "xx@developer.gserviceaccount.com";  // 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));

我已经使用了Fiddler,我可以看到令牌是如何在谷歌和我的应用程序之间"飞行"的,但我没有任何选择。

我需要做一些类似于Python上的代码,但在c#中使用嵌入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

如果你阅读关于Embed Api的文档,你会发现你需要令牌…

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

有了这些信息…我如何获得服务令牌??谢谢! !

这对我有用

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%>'
    }
});

只是为了添加到https://stackoverflow.com/a/38218844/5334191,.netcore:

    public async Task<string> Token(Microsoft.AspNetCore.Hosting.IWebHostEnvironment webenv)
    {
            var root = webenv.ContentRootPath;
            var file = System.IO.Path.Combine(root, "googleanalytics.json");
            Google.Apis.Auth.OAuth2.GoogleCredential credential = GoogleCredential.FromFile(file);
            credential = credential.CreateScoped(new[] {"https://www.googleapis.com/auth/analytics.readonly" });
            var result = await ((ITokenAccess)credential).GetAccessTokenForRequestAsync();
            return result;
    }

创建ServiceAccountCredential已经很好了。接下来你需要做的是在ServiceAccountCredential实例上调用RequestAccessTokenAsync(),之后该实例将使用访问令牌填充其Token属性,例如

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

最新更新