从API项目请求Google Apis Oauth2权限

时间:2018-08-14 07:36:08

标签: asp.net asp.net-core google-api google-sheets-api google-api-dotnet-client

该Web应用程序由多个项目构建而成。在这个问题中,我们将仅使用webapi项目。

api项目如何请求Google OAuth2权限来读取私人电子表格?

尝试1 -使用OAuth客户端凭据-仅在web项目上有效,因为它需要打开浏览器窗口,而api无法做到这一点。

            string[] scopes = { SheetsService.Scope.SpreadsheetsReadonly };

            var secrets = new Google.Apis.Auth.OAuth2.ClientSecrets()
            {
                ClientId = _configuration["Google:client_id"],
                ClientSecret = _configuration["Google:client_secret"]
            };

            var credential
                = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets, scopes, "My Project", CancellationToken.None)
                  .Result;

            var service = new Google.Apis.Sheets.v4.SheetsService(
                new Google.Apis.Services.BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "My Project",
                });

            Google.Apis.Sheets.v4.SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            Google.Apis.Sheets.v4.Data.ValueRange response = request.Execute();

尝试2 -使用服务帐户密钥-可以在API中使用,但是无法请求访问私人文档。

            string[] scopes = { SheetsService.Scope.SpreadsheetsReadonly };

            var credential = Google.Apis.Auth.OAuth2.GoogleCredential
                .FromJson(_googleSecret).CreateScoped(scopes);

            var service = new Google.Apis.Sheets.v4.SheetsService(
                new Google.Apis.Services.BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "My Project",
                });

            Google.Apis.Sheets.v4.SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            Google.Apis.Sheets.v4.Data.ValueRange response = request.Execute();

尝试3 -使用API​​密钥-仅适用于公共文档

             var service = new Google.Apis.Sheets.v4.SheetsService(
                new Google.Apis.Services.BaseClientService.Initializer()
                {
                    ApiKey = _configuration["Google:api_key"],
                    ApplicationName = "My Project",
                });

            Google.Apis.Sheets.v4.SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            Google.Apis.Sheets.v4.Data.ValueRange response = request.Execute();

0 个答案:

没有答案