Я пишу настольное приложение на C#, которое должно иметь доступ ко всем пользователям в учетной записи Google Apps для получения календарных событий для каждого пользователя. Я добавил API календаря и SDK администратора в свой «проект».Несколько разрешений доступа Google для настольного приложения
Оба метода (ниже) работают отлично самостоятельно, но когда я хочу авторизовать свое приложение для обоих API, я получаю следующие ошибки разрешения.
Недостаточное Разрешение [403]
invalid_grant "Описание:" Знак был аннулирован.
Это заставило меня задаться вопросом, можно ли запрашивать все разрешения при запуске приложения, а не разрешать «функции» отдельно?
static string[] CalendarScopes = {CalendarService.Scope.CalendarReadonly };
static string[] DirectoryScopes = { DirectoryService.Scope.AdminDirectoryUserReadonly };
private static void GoogleCalendar()
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
CalendarScopes,
"user",
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.");
}
Console.Read();
}
private static void GoogleDirectory()
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(
Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
DirectoryScopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Directory API service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.ListRequest request = service.Users.List();
request.Customer = "my_customer";
request.MaxResults = 10;
request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
// List users.
IList<User> users = null;
try
{
users = request.Execute().UsersValue;
}
catch (Exception ex)
{
throw;
}
Console.WriteLine("Users:");
if (users != null && users.Count > 0)
{
foreach (var userItem in users)
{
Console.WriteLine("{0} ({1})", userItem.PrimaryEmail,
userItem.Name.FullName);
}
}
else
{
Console.WriteLine("No users found.");
}
Console.Read();
}
какие ошибки вы получаете? Да, вы можете запросить маркер доступа со всеми областями, которые потребуются для вашего приложения. Хотя это не рекомендуется. – Gerardo
Я обновил свой вопрос за исключениями. Почему не рекомендуется использовать токен доступа для нескольких областей? –