Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

oauth 2.0 - How to make CalendarService object using access_token?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...