Google API OAuth 2:使用授权代码作为Google的字符串';的.NET库

本文关键字:Google 字符串 NET 代码 OAuth API 授权 | 更新日期: 2023-09-27 17:59:55

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

从谷歌上的另一个文档页面上,我学会了如何通过浏览器请求获得授权密钥。这发生在控制台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();

在最后一行,打开了一个浏览器窗口,其中有一个谷歌页面,要求我允许应用程序访问我的谷歌帐户。在控制台应用程序中,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应用程序中使用此功能,而不是控制台应用程序。我没有能够在谷歌的页面上找到任何关于这方面的信息。

到目前为止我所拥有的:

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

我有一种感觉,使用谷歌的REST客户端而不是本机.NET库是可能的,但我真诚地希望使用.NET库而不是REST.

Google API OAuth 2:使用授权代码作为Google的字符串';的.NET库

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

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