Google Calendar API服务帐户错误401凭据无效

问题描述 投票:1回答:1

我正在尝试创建Google日历服务帐户。

这是我的凭据:

enter image description here

这是我的服务帐户定义(已启用服务帐户的站点范围委派):

enter image description here

这是我的“管理API客户端访问”页面:

enter image description here

这是我的代码:

        string userName = "[email protected]";
        string[] Scopes = { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarEvents };
        string ApplicationName = "Client per quickstart";
        ServiceAccountCredential credential = GoogleCredential.FromFile(@"path\credentialjson.json").CreateScoped(Scopes).CreateWithUser(userName).UnderlyingCredential as ServiceAccountCredential;

        // Create Google Calendar API service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName
        });
        // THIS REQUEST FAILS!!  
        var y = service.CalendarList.List().Execute(); 

服务已正确创建,但所有请求均失败,并显示以下错误:

代码:401,消息:“无效凭据”,位置:“授权”,> LocationType:“标题”,原因:“ authError”,域:“全局”

我不明白授权标头中缺少什么。

在创建服务时未完成的请求之前,我应该设置什么?谢谢!

c# google-api google-calendar-api google-api-dotnet-client service-accounts
1个回答
0
投票

您是否在凭据上方看到文本?>

OAuth 2.0客户端ID

转到Google Developer Console,单击+ create credentials从下拉列表中选择服务帐户。您需要确保已为服务帐户而不是Oauth2客户端下载了密钥。

服务帐户凭据的示例

enter image description here

您创建的是oauth2凭据,而不是服务帐户信用凭证。

GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Service account Authentication Sample",
                    });
© www.soinside.com 2019 - 2024. All rights reserved.