Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 谷歌分析报告授权服务帐户_C#_.net_Google Api_Google Analytics Api_Google Api Dotnet Client - Fatal编程技术网

C# 谷歌分析报告授权服务帐户

C# 谷歌分析报告授权服务帐户,c#,.net,google-api,google-analytics-api,google-api-dotnet-client,C#,.net,Google Api,Google Analytics Api,Google Api Dotnet Client,我正在尝试使用google analytics API使用服务帐户在c#webapp中报告用户信息 我已经下载了JWT文件并将其链接到项目中。 我在尝试验证服务帐户时遇到了一个问题:当我调用RequestAccessTokenAsync(cancellationToken)anc异常时抛出,表示作用域不能为空值,我无法设置作用域,因为我正在从json流创建serviceAccountCredential 另一种选择是使用serviceAccountCredential.GetAccessToke

我正在尝试使用google analytics API使用服务帐户在c#webapp中报告用户信息

我已经下载了JWT文件并将其链接到项目中。 我在尝试验证服务帐户时遇到了一个问题:当我调用
RequestAccessTokenAsync(cancellationToken)
anc异常时抛出,表示作用域不能为空值,我无法设置作用域,因为我正在从json流创建
serviceAccountCredential

另一种选择是使用
serviceAccountCredential.GetAccessTokenForRequestAsync(serviceAccountCredential.TokenServerUrl)
请求访问令牌,但在这种情况下,我不知道如何将该令牌提供给报告请求,没有该令牌,API调用将不会被授权并将失败

这是源代码:

string viewId = "VIEW_ID";      
FileStream jwtSecretStream = new FileStream(@"path\to\servicesecret.json", FileMode.Open, FileAccess.Read);
var metrics = new List<Metric> { new Metric { Expression = "ga:users" } };
var dimensions = new List<Dimension> { new Dimension { Name = "ga:userType" } };
DateRange dateRange = new DateRange
{
     StartDate = DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
     EndDate = DateTime.UtcNow.ToString("yyyy-MM-dd")
};
try
{
     serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(jwtSecretStream);
     // this call will throw the exception
     var x = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None); 
    //this call will return a valid token -> DON'T KNOW HOW TO PASS To THE REQUEST
    //var y = await serviceAccountCredential.GetAccessTokenForRequestAsync(serviceAccountCredential.TokenServerUrl); 
}
catch (Exception e)
{
    throw;
}
_analyticsReportingService = new AnalyticsReportingService(new AnalyticsReportingService.Initializer()
{
    HttpClientInitializer = serviceAccountCredential,
    //HttpClientInitializer = credential,
    ApplicationName = "TestAnalytics",
});
//If I execute the request I got UNAUTHORIZED because there's not a valid access token  
var response = _analyticsReportingService.Reports.BatchGet(getReportRequest).Execute();
string viewId=“VIEW\u ID”;
FileStream jwtSecretStream=newfilestream(@“path\to\servicesecret.json”,FileMode.Open,FileAccess.Read);
var metrics=new List{new Metric{Expression=“ga:users”};
var dimensions=newlist{new Dimension{Name=“ga:userType”};
DateRange DateRange=新的日期范围
{
StartDate=DateTime.UtcNow.AddDays(-7).ToString(“yyyy-MM-dd”),
EndDate=DateTime.UtcNow.ToString(“yyyy-MM-dd”)
};
尝试
{
serviceAccountCredential=serviceAccountCredential.FromServiceAccountData(jwtSecretStream);
//此调用将引发异常
var x=等待serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None);
//此调用将返回一个有效令牌->不知道如何传递到请求
//var y=等待serviceAccountCredential.GetAccessTokenForRequestAsync(serviceAccountCredential.TokenServerUrl);
}
捕获(例外e)
{
投掷;
}
_analyticsReportingService=new analyticsReportingService(new analyticsReportingService.Initializer())
{
HttpClientInitializer=serviceAccountCredential,
//HttpClientInitializer=凭证,
ApplicationName=“TestAnalytics”,
});
//如果我执行该请求,我将未经授权,因为没有有效的访问令牌
var response=_analyticsReportingService.Reports.BatchGet(getReportRequest.Execute();

如何为服务帐户提供有效的作用域,或者请求访问令牌并将其放入批处理请求中?

这是我通常用于验证服务的代码

//
///使用服务帐户向Google进行身份验证
///文件:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// 
///从谷歌开发者控制台https://console.developers.google.com
///从Google开发者控制台下载的.p12或Json服务帐户密钥文件的位置https://console.developers.google.com
///AnalyticsService用于针对Analytics API发出请求
公共静态分析报告服务AuthenticateServiceAccount(字符串serviceAccountEmail、字符串serviceAccountCredentialFilePath、字符串[]作用域)
{
尝试
{
if(string.IsNullOrEmpty(serviceAccountCredentialFilePath))
抛出新异常(“需要服务帐户凭据文件的路径”);
如果(!File.Exists(serviceAccountCredentialFilePath))
抛出新异常(“服务帐户凭据文件不存在于:“+serviceAccountCredentialFilePath”);
if(string.IsNullOrEmpty(serviceAccountEmail))
抛出新异常(“需要ServiceAccountEmail”);
//对于Json文件
if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.json”)
{
谷歌认证证书;
使用(var stream=newfilestream(serviceAccountCredentialFilePath,FileMode.Open,FileAccess.Read))
{
credential=GoogleCredential.FromStream(流)
.CreateScoped(范围);
}
//创建分析服务。
返回新的AnalyticsreportingService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“Analyticsreporting服务帐户验证示例”,
});
}
else if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.p12”)
{//如果是P12文件
var证书=新的X509Certificate2(serviceAccountCredentialFilePath,“notasecret”,X509KeyStrageFlags.MachineKeySet | X509KeyStrageFlags.Exportable);
var凭证=新ServiceAccountCredential(新ServiceAccountCredential.Initializer(serviceAccountEmail)
{
范围=范围
}.FromCertificate(证书));
//创建Analyticsreporting服务。
返回新的AnalyticsreportingService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“Analyticsreporting身份验证示例”,
});
}
其他的
{
抛出新异常(“不支持的服务帐户凭据”);
}
}
捕获(例外情况除外)
{                
抛出新异常(“CreateServiceAccountAnalyticsreportingFailed”,ex);
}
}
}
服务账户奖金信息

服务帐户是虚拟用户。默认情况下,他们有自己的google驱动器帐户google calendar,可能还有更多。默认情况下,他们没有谷歌分析账户

“用户没有google analytics帐户403禁止”

当用户试图访问Google analytics api而不采取行动时,会出现此消息
/// <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, string[] scopes)
    {
        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.");                

            // 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)
        {                
            throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
        }
    }
}