【问题标题】:Google API OAuth 2: Use authorization code as a string with Google's .NET librariesGoogle API OAuth 2:在 Google 的 .NET 库中使用授权码作为字符串
【发布时间】:2023-03-26 04:20:02
【问题描述】:

我的 WinForms 应用需要访问其中一个 Google API(日历)。为此,该应用程序需要获得授权,谷歌为此提供了 OAuth 2。我已经阅读了他们文档网站 here 上的所有内容。

从 Google 上的另一个文档页面,我了解了如何通过浏览器请求获取授权密钥。这发生在控制台 C# 应用程序中。它的作用是:

var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new CalendarService(auth);
string id = <calendar id>;
Calendar calendar = service.Calendars.Get(id).Fetch();

在最后一行,会打开一个浏览器窗口,其中包含一个 Google 页面,要求我允许该应用访问我的 Google 帐户。在控制台应用程序中,ReadLine() 正在等待输入。这来自GetAuthorization 方法:

private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
    // Get the auth URL:
    IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
    Uri authUri = arg.RequestUserAuthorization(state);

    // Request authorization from the user (by opening a browser window):
    Process.Start(authUri.ToString());
    Console.Write("  Authorization Code: ");
    string authCode = Console.ReadLine();
    Console.WriteLine();

    // Retrieve the access token by using the authorization code:
    return arg.ProcessUserAuthorization(authCode, state);
}

因此,我授予我的应用访问我的 Gmail 帐户的权限,作为回报,我得到了一个代码。我将此代码粘贴回控制台窗口,然后应用程序的其余部分按应有的方式工作(在我的情况下,创建一个新的日历事件)。

但我的问题是我希望在 WinForms 应用程序中使用此功能,而不是在控制台应用程序中。我没有在 Google 的网页上找到与此相关的任何内容。

到目前为止我所拥有的:

  • 用户单击按钮,浏览器打开,用户授予访问权限并检索代码。
  • 用户将此代码粘贴到应用程序中。
  • 单击了另一个按钮,我想在此处使用用户输入的代码进行授权过程。这是一个字符串,我不知道如何将它与本文顶部编写的所有身份验证方法结合起来。

我感觉可以使用 Google 的 REST 客户端而不是原生 .NET 库,但我真诚地希望使用 .NET 库而不是 REST。

【问题讨论】:

    标签: c# winforms google-api oauth-2.0 google-api-dotnet-client


    【解决方案1】:

    看看AuthorizationMgr 类,特别是RequestNativeAuthorization 方法。它使用LoopbackServerAuthorizationFlow 类,它为您创建了一个 tcp 侦听器并从传入请求中获取代码。

    您还应该查看使用该机制的示例之一(例如CreateTask 示例)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2012-07-14
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多