【问题标题】:Is there a way to reuse Google.Apis.Auth.OAuth2.UserCredential object to authorize SpreadsheetsService?有没有办法重用 Google.Apis.Auth.OAuth2.UserCredential 对象来授权 SpreadsheetsService?
【发布时间】:2015-04-24 05:01:45
【问题描述】:

我正在尝试通过 C# 控制台应用程序使用 Google Drive 和 Spreadsheets API。我想使用带有FileDataStore 的用户凭据来授权这两个服务,这样我就不必在每次运行时都重新验证我的应用程序。下面是我如何授权我的 Drive 服务对象:

var userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync
(
  new ClientSecrets 
  { 
    ClientId = "[clientID]", 
    ClientSecret = "[clientSecret]" 
  },
  new [] 
  { 
    "https://www.googleapis.com/auth/drive",    
    "https://spreadsheets.google.com/feeds" 
  },
  "[userName]",
  CancellationToken.None,
  new FileDataStore("MyApp.GoogleDrive.Auth.Store")
).Result;

var driveService = new DriveService
(
  new BaseClientService.Initializer
  {
    HttpClientInitializer = userCredential,
    ApplicationName       = "MyApp",
  }
);

对于电子表格服务,我按照this guide 的规定进行授权,但每次运行我的应用程序时,我都必须打开浏览器访问给定的身份验证 URL 并手动复制访问令牌以使其工作.

有没有一种方法可以进行一次身份验证,获取上述用户凭据,并将它们用于两种服务?请注意,我正在对 Drive 和 Spreadsheets 范围进行授权,所以我认为这没有问题。

我试图让它像这样工作,但是当我尝试将行插入电子表格时,我不断收到 400 Bad Request 错误:

var auth = new OAuth2Parameters 
{ 
  ClientId     = "[clientID]",
  ClientSecret = "[clientSecret]",
  RedirectUri  = "[redirectUri]",
  Scope        = "https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds" ,
  AccessToken  = userCredential.Token.AccessToken,
  RefreshToken = userCredential.Token.RefreshToken,
  TokenType    = userCredential.Token.TokenType,
};

var requestFactory = new GOAuth2RequestFactory(null, "MyApp", auth);

var spreadsheetsService = new SpreadsheetsService("MyApp") 
{ 
  Credentials    = new GDataCredentials(userCredential.Token.TokenType + " " + userCredential.Token.AccessToken),
  RequestFactory = requestFactory,
};

【问题讨论】:

    标签: c# google-drive-api google-spreadsheet-api


    【解决方案1】:

    有没有一种方法可以验证一次,获取上述用户凭据,然后将它们用于这两种服务?

    是的。如果您已包含所有范围并已请求离线访问,那么您将获得一个刷新令牌,您可以存储和重用该令牌以根据需要获取访问令牌。 Obv 您需要考虑安全隐患。

    400 错误请求听起来不像是 OAuth 问题。我认为您在这里有两个问题/问题,可能值得开始一个新线程。在您的问题中包含 400 的 http 请求/响应。

    【讨论】:

    • 你说得对。我的错误实际上与身份验证无关。它更进一步。
    猜你喜欢
    • 2016-08-24
    • 2020-06-26
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多