Google身份验证流程

时间:2012-03-20 17:45:31

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

我正在尝试编写一个原生应用来访问用户谷歌日历。我正在尝试使用谷歌提供的示例来获取身份验证,但它似乎永远不会启动身份验证功能

private void Window_Initialized(object sender, EventArgs e)
{
    var provider = new NativeApplicationClient(
            GoogleAuthenticationServer.Description);
    provider.ClientIdentifier = "<My Client Id here>";
    provider.ClientSecret = "<My Client Secret here";

    var auth = new OAuth2Authenticator<NativeApplicationClient>(
        provider, (p) => GetAuthorization(provider));

    CalendarService service = new CalendarService();
    CalendarsResource.GetRequest cr = service.Calendars.Get("{primary}");

    if (cr.CalendarId != null)
    {
        Console.WriteLine("Fetching calendar");
        //Google.Apis.Calendar.v3.Data.Calendar c =
            service.Calendars.Get("{primary}").Fetch();
    }
    else
    {
        Console.WriteLine("Service not found");
    }
}

以下是我用于身份验证的代码。我从来没有看到控制台写信发布。

private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
    Console.WriteLine("Authorization Requested");

    IAuthorizationState state = new AuthorizationState(
        new[] { CalendarService.Scopes.Calendar.GetStringValue() });
    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
    Uri authUri = arg.RequestUserAuthorization(state);

    Process.Start(authUri.ToString());
    // Request authorization from the user and get the code
    string authCode = Console.ReadLine();

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

有没有更好的教程可用,或者我做错了什么?

3 个答案:

答案 0 :(得分:2)

示例代码已损坏。要使服务使用您的身份验证器,您需要连接它。在该示例中,服务和验证器之间没有关联。像这样创建服务:

var service = new CalendarService(new BaseClientService.Initializer()
{
    Authenticator = auth
};

请查看https://code.google.com/p/google-api-dotnet-client/以获取更好的文档/工作代码。

答案 1 :(得分:0)

查看新的docs。你需要更换

var auth = new OAuth2Authenticator<NativeApplicationClient>(
    provider, (p) => GetAuthorization(provider));

AuthenticatorFactory.GetInstance().RegisterAuthenticator(
    () => new OAuth2Authenticator(provider, GetAuthentication));

正如评论所说,当您致电var service = new CalendarService()时,将自动调用之前注册的身份验证器。

答案 2 :(得分:0)

我认为以上方式与旧版Google日历DLL有关。有没有人知道新版Google日历的文档,即V 1.8.1.82。 Google从未为.NET developer.s提供良好的文档。