Google Authentication Process

joshwl2003 picture joshwl2003 · Mar 20, 2012 · Viewed 7.8k times · Source

I am trying to write a native app to access a users google calendar. I am trying to use the example that google has provided to get authentication but it never seems to fire the authentication function

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

Here is the code that I am using for Authentication. I never see the console writeline get published.

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

Are there any better tutorials available or am I doing something wrong?

Answer

mammo picture mammo · Apr 2, 2013

The example code is broken. To make the service use your authenticator, you need to connect it. In the example there is no association between the service and the authenticator. Create the service like this:

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

Look at https://code.google.com/p/google-api-dotnet-client/ for better documentation/working code.