且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 access_token 创建 CalendarService 对象?

更新时间:2023-02-20 13:20:10

这个问题大约在一年前被问到,但无论如何这里是我用来初始化只有 accessToken 的 CalendarService 的代码.

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

起初,我基于其源代码实现了 UserCredential 类的克隆",但删除了与 Google APIs OAuth2 方法相关的所有不必要的人员

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

之后,创建 CalendarService 的实例看起来非常简单:

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