6

I am trying to use google calendar v3 api using .net client. I am follwing a hybrid approach. I have authorized my application using oauth2 using only http post request and I get the access_token. But as .net client of calendar v3 api, I need to make a calendarservice reference. I need to find any way to get that service reference using my token. Have a look at this code snippet:

Event event = new Event()
{
  Summary = "Appointment",     
};

Event recurringEvent = service.Events.Insert(event, "primary").Fetch();
// here "service" is authenticate calendarservice instance.

Console.WriteLine(recurringEvent.Id);

and this is the code to get authenticated calendarservice instance:

 UserCredential credential;
 using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
 {
      credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { CalendarService.Scope.Calendar },
                "user", CancellationToken.None, new FileDataStore("something"));
 }

  // Create the service instance.
  var service = new CalendarService(new BaseClientService.Initializer()
  {
          HttpClientInitializer = credential,
          ApplicationName = "Books API Sample",
  });

This code shows the authorization code flow according to Google.Apis.Auth.OAuth2 and then make service reference using that credential. Actually this is a helper utility to manage authorization code flow. To be clear, I am not using this procedure.(this helper utility). I am trying to do everything in core level that means I have made authorization code flow manually by simple HTTP web request. And I have done authorization perfectly. Now I have that users access_token.

Now my question is that how can I create this service instance manually only using that access_token. If anything bother you, feel free to ask anything.

N.B - I know how to create CalendarService instance:

 var service = new CalendarService();

but how can I create this type instance with connected to authenticated token which I have.

Hannan Hossain
  • 740
  • 1
  • 12
  • 23

4 Answers4

13

The question was asked about a year ago but anyway here is the code I use to initialize CalendarService having accessToken only.

At first, I implemented a "clone" of UserCredential class based on its source code but removing all unnecessary staff related to Google APIs OAuth2 methods

internal class CustomUserCredential : IHttpExecuteInterceptor, IConfigurableHttpClientInitializer
{
    private string _accessToken;

    public CustomUserCredential(string accessToken)
    {
        _accessToken = accessToken;
    }

    public void Initialize(ConfigurableHttpClient httpClient)
    {
        httpClient.MessageHandler.ExecuteInterceptors.Add(this);
    }

    public async Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
    }
}

After that, creating an instance of CalendarService looks pretty simple:

private CalendarService GetCalendarService(string accessToken)
    {
        return new CalendarService(new BaseClientService.Initializer
            {
                HttpClientInitializer = new CustomUserCredential(accessToken),
                ApplicationName = "AppName"
            });
    }
Alexey Gurevski
  • 481
  • 5
  • 12
  • This was enormously helpful. Is there a good reason for a simple class like this not being a part of the .NET API? This problem mostly took me a long time to figure out because I was sure that I simply wasn't finding the correct classes in the API. It was surprising to find out that they don't exist for doing basic oauth2 authentication to the API. – cl0rkster Jan 03 '16 at 19:29
  • This is really helpful. Thank you @AlexeyGureski. – NJ Bhanushali Feb 15 '16 at 12:24
  • Alexey, you can add that answer to my question here: http://stackoverflow.com/questions/41039044/using-the-google-api-net-client-with-an-existing-access-token and I will mark it as answer! Thanks for your help. – ThomasWeiss Dec 13 '16 at 06:02
  • This worked for AnalyticsReportingService as well to enable report extracts from Google Analytics UA – markblue777 Oct 26 '22 at 13:43
0

The example you uses FileDataStore.

How FileDataStore works - The first time you run the code it will ask the user if they want to let you access there calender. The information is then stored in your %appData% directory. If you want to load a refresh token that you have for example stored in the database you cant.

Stored Refreshtoken - In order to use a refreshToken that you for example have stored in the database you need to create your own implimitation of IdataStore. Once you have done that you will be able to send the refresh token that you saved previously.

This tutorial should help you understand http://www.daimto.com/google-oauth2-csharp/

You dont need to deal with getting new access token the Service will use the RefreshTokens to get a new access token for you.

If this doesnt help post a comment and i will see if i can expend it a little more.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • @DalmTo I didn't use FileDataStore. I have given that code to know how to do that manually. I have gained access_token manually by using http request to api. Now I need to make that service reference using that access_token. Did you get my point? – Hannan Hossain Feb 05 '14 at 14:35
  • your code has new FileDataStore("something")); And you state that your using calendar v3 api. Createing all of the oauth2 calls yourself requires a little more work. check this link let me know if you need any help: http://www.daimto.com/google-api-and-oath2/ – Linda Lawton - DaImTo Feb 05 '14 at 14:41
  • @DalmTo Please see my edit in the question. I have added some more information to clear my problem. I think you will get that. I am not using that helper utilty class provided by google calendar. I am doing it manually. And I have completed authorization process successfully. Just need to make that Service reference using that access_token to use .net client. – Hannan Hossain Feb 05 '14 at 15:12
0

I like @alexey's response the best but as an alternative you can initialize with the simple constructor and then pass the access token in on each request, like this:

// Create service
var service = new CalendarService();

// Request
var request = service.Events.Get("x", "y");
request.OauthToken = accessToken;
var response = request.Execute();
fredw
  • 1,409
  • 12
  • 23
-1

Your solution should look very similar to this one: .NET Google api 1.7 beta authenticating with refresh token

Remember to set the ExpiresInSeconds and Issued properties, so the library won't think that the access_token has expired (https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.Auth/OAuth2/Responses/TokenResponse.cs#66)

Community
  • 1
  • 1
peleyal
  • 3,472
  • 1
  • 14
  • 25