gpt4 book ai didi

c# - 从 Google 中的客户端电子邮件和私钥(服务帐户)获取 token

转载 作者:行者123 更新时间:2023-11-28 16:30:00 25 4
gpt4 key购买 nike

我花了很多时间试图获得授权 token 。

我需要向我的用户展示一些收集到的 Analytics 信息(我是 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 = "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,我可以看到 token 如何在 Google 和我的应用程序之间“飞行”,但我没有任何选择来接受它。

我需要做一些类似 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

如果您阅读有关 Embed Api 的文档,您会发现您需要 token ...

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

有了所有这些信息...我怎样才能获得服务 token ???谢谢!!

最佳答案

这对我有用

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

关于c# - 从 Google 中的客户端电子邮件和私钥(服务帐户)获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com