【问题标题】:.NET Google api 1.7 beta authenticating with refresh token.NET Google api 1.7 beta 使用刷新令牌进行身份验证
【发布时间】:2019-02-09 07:20:32
【问题描述】:

我一直在查看 Oauth .Net Google API,以便通过 OAuth 进行身份验证并使用 Google drive API。

具体来说,我想使用我已经存储的刷新令牌来实例化 GoogleDrive 服务。

我找到了类似的样本 https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples

这似乎使用“GoogleWebAuthorizationBroker.AuthorizeAsync”,但我不确定如何使用刷新令牌而不是您在本示例中提供的客户端机密来使用该方法。

【问题讨论】:

  • 几个cmets。 OAuth 用于授权,而不是身份验证(尽管它有点作为副产品进行身份验证)。当您说“现有刷新令牌”时,请确保刷新令牌是使用适当的驱动器范围生成的。由于您已经拥有刷新令牌,因此无需再次授权,因此您将不会使用 GoogleWebAuthorizationBroker。我对 .NET 的了解不足以完全回答您的问题,但从已经发布的答案来看,来自 peleyal 的答案是最接近的。
  • 谢谢大家。你给了我很多好的线索来跟进。

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


【解决方案1】:

如果我理解正确,您是在问如何根据现有的刷新令牌创建新的 Google 服务。

因此,您可以执行以下操作:

var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" }; 
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer 
    {
      ClientSecrets = [your_client_secrets_here]
    }), "user", token);

然后您可以将您的凭据传递给服务的初始化程序。

通过执行上述操作,GoogleAuthorizationCodeFlow 将根据您刷新令牌和客户端机密获取新的访问令牌。

请注意,您必须在此处拥有客户端密码,否则您将无法获得访问令牌。

【讨论】:

  • 这似乎接近我想要的。我会跟进这件事。而且我确实有我的应用程序设置的客户端机密。谢谢。
  • 正是我需要的并且在我的代码中正常工作。非常感谢。
  • 对于最终在这里的其他人,上述方法取代了以前版本中的“IAuthenticator”技术,该技术仍然是文档、示例应用和 SO 答案中的功能。
  • 如何获得“YOUR_REFRESH_TOKEN_HERE”?
  • 如何从现有的文件数据存储对象中获取REFRESH TOKEN?
【解决方案2】:

client_secrets.json 包含客户端 ID 和客户端密码(其中包含您的应用程序的 OAuth 2.0 信息)。

我认为本文将更好地解释如何通过 OAuth 2.0 访问 Google Apps API,尤其是在构建 Web 应用程序时。

https://developers.google.com/accounts/docs/OAuth2WebServer

如果你对编码示例感兴趣,stackoverflow 中有一个:Google+ API: How can I use RefreshTokens to avoid requesting access every time my app launches?

【讨论】:

  • 谢谢艾米丽。我过去确实看到并使用过该代码示例,它确实有效。但使用“NativeApplicationClient”使用 OAuth 似乎是旧的过时方法。我想新东西有所有新的结构可以使用。再次感谢!
【解决方案3】:

GoogleWebAuthorizationBroker 要求您向它发送 iDataStore 的暗示,在这种情况下发送 FileDatastore。 FileDataStore 将数据存储在 %appData% 中。如果您想使用保存在其他地方的刷新令牌,您需要创建自己的 iDataStore 限制。

实际数据存储的代码有点长,我在这里发布。 http://daimto.com/google-oauth2-csharp/

然后您可以像使用 FileDataStore 一样使用它

//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
 using (var stream = new FileStream("client_secrets.json", FileMode.Open,
        FileAccess.Read))
  {
     GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
     StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
     GoogleClientSecrets.Load(stream).Secrets,
     new[] { DriveService.Scope.Drive,
     DriveService.Scope.DriveFile },
     "user",
      CancellationToken.None,
      new SavedDataStore(myStoredResponse)).Result;
     }

该教程附有一个示例项目。

【讨论】:

  • 我看到那个文件数据存储并认为它可能包含一个刷新令牌,我只是找不到任何信息。感谢您的链接
【解决方案4】:

使用刷新令牌:

var init = new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = "OAuth_Client_ID_From_GoogleAPI",
        ClientSecret = "OAuth_Client_Secret"
    },
    Scopes = new string[] {"MY_SCOPES"}
};
var token = new TokenResponse { RefreshToken = "MY_REFRESH_TOKEN" };
var credential = new UserCredential(new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(init), "", token);

//init your Google API service, in this example Google Directory
var service = new DirectoryService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "",
});

如果您没有刷新令牌怎么办?最简单的方法是按照 Google SDK 文档上的说明进行操作。第一的 从 Google API 项目下载您的凭据。将文件命名为credentials.json。然后运行代码:

using (var stream =
    new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
    // The file token.json stores the user's access and refresh tokens, and is created
    // automatically when the authorization flow completes for the first time.
    string credPath = "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "user",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
    Console.WriteLine("Credential file saved to: " + credPath);
}

这应该创建一个文件夹 token.json 并且里面的文件夹是另一个包含你的 json 文件 刷新令牌。

{
    "access_token" : "asdf",
    "token_type" : "Bearer",
    "expires_in" : 3600,
    "refresh_token" : "XXX",
    "scope" : "https://www.googleapis.com/auth/admin.directory.user.readonly",
    "Issued" : "2019-02-08T12:37:06.157-08:00",
    "IssuedUtc" : "2019-02-08T20:37:06.157Z"
}

我不喜欢使用 GoogleWebAuthorizationBroker,因为它会在以下情况下自动启动网络浏览器 找不到令牌。我更喜欢通过访问代码获取刷新令牌的老式方法。 这与使用 Google OAuthUtil.CreateOAuth2AuthorizationUrlOAuthUtil.GetAccessToken 非常相似 在 Google 的旧版 OAuth API 中。

var a = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = "asdf",
        ClientSecret = "hij"
    },
    Scopes = Scopes
};
var flow = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(a);
var url = flow.CreateAuthorizationCodeRequest(GoogleAuthConsts.InstalledAppRedirectUri).Build().AbsoluteUri;
Console.WriteLine("Go to this URL and get access code: " + url);

Console.Write("Enter access code: ");
var code = Console.ReadLine();

Console.WriteLine("Fetching token for code: _" + code + "_");
var r = flow.ExchangeCodeForTokenAsync("user", code, GoogleAuthConsts.InstalledAppRedirectUri, CancellationToken.None).Result;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(r));

【讨论】:

  • 重要提示!为了让它不启动网络浏览器,您可以在新的 FileDataStore() 之后解析 GoogleWebAuthorizationBroker.AuthorizeAsync() 内的新 PromptCodeReceiver() 的参数!本质上,这将与您显示的第四部分代码相同,提示用户而不是打开浏览器。不过很酷的东西!
猜你喜欢
  • 2017-11-08
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 2011-11-13
相关资源
最近更新 更多