Oauth 2- 如何使用刷新令牌
Oauth 2- how to use refresh token
我正在使用 Google Api 更改用户日历 - 与客户端应用程序中的日历同步。我找不到任何关于如何以及何时使用刷新令牌的教程。下面是我的测试应用程序,用于读取 from/write 到 google 日历。如何检查访问令牌是否过期,我应该在哪里检查以及如何刷新令牌?
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CalendarQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.Calendar };
static string ApplicationName = "test";
static void Main(string[] args)
{
UserCredential credential;
using (var stream = new FileStream("NewFolder1/client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/test.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user1234",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
/////////////
Event newEvent = new Event()
{
Summary = "Google I/O 2015",
Description = "A chance to hear more about Google's developer products.",
Start = new EventDateTime()
{
DateTime = DateTime.Now,
},
End = new EventDateTime()
{
DateTime = DateTime.Now.AddHours(1),
},
};
String calendarId = "primary";
EventsResource.InsertRequest requestInsertEvent = service.Events.Insert(newEvent, calendarId);
Event createdEvent = requestInsertEvent.Execute();
Console.WriteLine("Event created: {0}", createdEvent.Id);
/////////////
Console.Read();
}
}
}
您无需测试访问令牌是否过期,客户端库会为您处理。
但是,如果出于某种原因您确实想要,可以将其发送至
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg
如果无效,将return 出错。
DaImTo 是对的,您无需担心,客户端库会为您完成。
此处提供教程和更多详细信息:
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#acquiring--client-ids-and-secrets
包括提及以下内容的 User Credential 部分:
UserCredential 和 AuthorizationCodeFlow 自动处理 "refreshing" 令牌,这仅意味着获取新的访问令牌。这是使用长期刷新令牌完成的,如果您在授权代码流中使用 access_type=offline 参数,您将与访问令牌一起收到该令牌。
我正在使用 Google Api 更改用户日历 - 与客户端应用程序中的日历同步。我找不到任何关于如何以及何时使用刷新令牌的教程。下面是我的测试应用程序,用于读取 from/write 到 google 日历。如何检查访问令牌是否过期,我应该在哪里检查以及如何刷新令牌?
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CalendarQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.Calendar };
static string ApplicationName = "test";
static void Main(string[] args)
{
UserCredential credential;
using (var stream = new FileStream("NewFolder1/client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/test.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user1234",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
/////////////
Event newEvent = new Event()
{
Summary = "Google I/O 2015",
Description = "A chance to hear more about Google's developer products.",
Start = new EventDateTime()
{
DateTime = DateTime.Now,
},
End = new EventDateTime()
{
DateTime = DateTime.Now.AddHours(1),
},
};
String calendarId = "primary";
EventsResource.InsertRequest requestInsertEvent = service.Events.Insert(newEvent, calendarId);
Event createdEvent = requestInsertEvent.Execute();
Console.WriteLine("Event created: {0}", createdEvent.Id);
/////////////
Console.Read();
}
}
}
您无需测试访问令牌是否过期,客户端库会为您处理。
但是,如果出于某种原因您确实想要,可以将其发送至
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg
如果无效,将return 出错。
DaImTo 是对的,您无需担心,客户端库会为您完成。
此处提供教程和更多详细信息: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#acquiring--client-ids-and-secrets 包括提及以下内容的 User Credential 部分:
UserCredential 和 AuthorizationCodeFlow 自动处理 "refreshing" 令牌,这仅意味着获取新的访问令牌。这是使用长期刷新令牌完成的,如果您在授权代码流中使用 access_type=offline 参数,您将与访问令牌一起收到该令牌。