How to make CalendarService object using access_token?

后端 未结 4 1104
我寻月下人不归
我寻月下人不归 2020-12-18 06:06

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

4条回答
  •  一向
    一向 (楼主)
    2020-12-18 06:37

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

提交回复
热议问题