该Web应用程序由多个项目构建而成。在这个问题中,我们将仅使用web
和api
项目。
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();