Han*_*ain 6 google-calendar-api oauth-2.0 google-api-dotnet-client
我正在尝试使用.net客户端使用谷歌日历v3 api.我正在采用混合方法.我只使用http post请求使用oauth2授权我的应用程序,我得到了access_token.但作为日历v3 api的.net客户端,我需要制作一个日历服务参考.我需要找到任何方法来使用我的令牌获取该服务引用.看看这段代码:
Event event = new Event()
{
Summary = "Appointment",
};
Event recurringEvent = service.Events.Insert(event, "primary").Fetch();
// here "service" is authenticate calendarservice instance.
Console.WriteLine(recurringEvent.Id);
Run Code Online (Sandbox Code Playgroud)
这是获取经过身份验证的日历服务实例的代码:
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",
});
Run Code Online (Sandbox Code Playgroud)
此代码根据Google.Apis.Auth.OAuth2显示授权代码流,然后使用该凭据进行服务引用.实际上,这是一个管理授权代码流的辅助工具.为了清楚起见,我没有使用这个程序.(这个助手实用程序).我正在尝试在核心级别执行所有操作,这意味着我已通过简单的HTTP Web请求手动创建了授权代码流.我完全完成了授权.现在我有那个用户access_token.
现在我的问题是如何仅使用该access_token手动创建此服务实例.如果有什么事打扰你,请随时提出任何问题.
注意 - 我知道如何创建CalendarService实例:
var service = new CalendarService();
Run Code Online (Sandbox Code Playgroud)
但是如何创建此类型实例并连接到我拥有的经过身份验证的令牌.
Ale*_*ski 10
大约一年前问过这个问题,但无论如何这里是我用来初始化只有accessToken的CalendarService的代码.
首先,我基于其源代码实现了UserCredential类的"克隆",但删除了与Google API OAuth2方法相关的所有不必要的人员
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);
}
}
Run Code Online (Sandbox Code Playgroud)
之后,创建CalendarService实例看起来非常简单:
private CalendarService GetCalendarService(string accessToken)
{
return new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = new CustomUserCredential(accessToken),
ApplicationName = "AppName"
});
}
Run Code Online (Sandbox Code Playgroud)
pel*_*yal -1
您的解决方案应该与以下解决方案非常相似: .NET Google api 1.7 beta authentiating withfresh token
请记住设置 ExpiresInSeconds 和 Issued 属性,这样库就不会认为 access_token 已过期(https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis. Auth/OAuth2/Responses/TokenResponse.cs#66)
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |