我使用谷歌API來做出與客戶端應用程序日曆用戶日曆]同步更改。我無法找到關於如何以及何時使用刷新令牌的任何教程。以下是我的測試應用程序來讀取/寫入谷歌日曆。我如何檢查訪問令牌是否過期,我應該在哪裏做以及如何刷新令牌?的Oauth 2-如何使用刷新令牌
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();
}
}
}
所以我並不需要做任何提神? – therko
不,您不使用文件數據存儲來存儲刷新令牌。客戶端庫擁有它們,並在需要時刷新訪問令牌。 – DaImTo