如何使用 C# 设置 OAuth 访问令牌

本文关键字:OAuth 访问令牌 设置 何使用 | 更新日期: 2023-09-27 18:34:36

我是C#和谷歌API的新手。

我有用于生成访问令牌的网址:

https://accounts.google.com/o/oauth2/auth?scope=https://spreadsheets.google.com/feeds& response_type=token& redirect_uri=https://developers.google.com/oauthplayground& client_id={my_client_ID}

答案是:
https://developers.google.com/oauthplayground/#access_token=ya29.iQLRHrmgKRmOnKnQjTqaBsmuCj4lV1m2wwhpA726wVNOGURIo2h6gTj1IdmGQ5Aa6OIrAQ& token_type=Bearer&expires_in=3599

我使用 https://developers.google.com/google-apps/spreadsheets 的这个例子来手动获取访问权限:

  string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
  Console.WriteLine(authorizationUrl);
  Console.WriteLine("Please visit the URL above to authorize your OAuth "
    + "request token.  Once that is complete, type in your access code to "
    + "continue...");
  parameters.AccessCode = Console.ReadLine();
  OAuthUtil.GetAccessToken(parameters);
  string accessToken = parameters.AccessToken;
  Console.WriteLine("OAuth Access Token: " + accessToken);
  GOAuth2RequestFactory requestFactory =
      new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
  SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
  service.RequestFactory = requestFactory;

如何使用 C# 通过链接获取access_token,然后将其用于我的电子表格?有没有.SetAccessToken(parameters(?

如何使用 C# 设置 OAuth 访问令牌

好吧,我自己解决了这个问题。代码为:

string CLIENT_ID = your_client_id;
string CLIENT_SECRET = your_client_secret;
string SCOPE = "https://spreadsheets.google.com/feeds";
string REDIRECT_URI = "https://developers.google.com/oauthplayground";
string REFRESH_TOKEN = your_refresh_token;
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
parameters.RefreshToken = REFRESH_TOKEN;
OAuthUtil.RefreshAccessToken(parameters);

现在您可以访问谷歌电子表格!