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

时间:2016-02-15 15:03:15

标签: c# oauth google-api google-sheets google-api-dotnet-client

我是C#和google api的新人。

我有访问令牌生成的URL:

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(参数)?

1 个答案:

答案 0 :(得分:1)

嗯,我自己解决了这个问题。 代码是:

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);

现在您可以访问Google电子表格了!