桌面应用程序的多个谷歌访问权限

本文关键字:访问 访问权 权限 谷歌 应用程序 桌面 | 更新日期: 2023-09-27 17:57:11

我正在用C#编写一个桌面应用程序,该应用程序应该能够访问Google Apps"帐户"上的所有用户,并为每个用户检索日历事件。我已将日历 API 和管理 SDK 添加到我的"项目"中。

这两种方法(如下)都可以单独工作正常,但是当我想为两个 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();
    }

桌面应用程序的多个谷歌访问权限

尤里卡!我想出了,如何解决问题,其实很简单。

解决方案是"合并"这些方法。这意味着,我只需使用访问令牌检查一次凭据。我还在作用域数组中添加了目录。

    static string[] Scopes = { CalendarService.Scope.CalendarReadonly, DirectoryService.Scope.AdminDirectoryUserReadonly };
    private static void GoogleThis()
    {
        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,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }
        // Create Google Calendar API service.
        var eventService = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        // Define parameters of request.
        EventsResource.ListRequest eventRequest = eventService.Events.List("primary");
        eventRequest.TimeMin = DateTime.Now;
        eventRequest.ShowDeleted = false;
        eventRequest.SingleEvents = true;
        //request.MaxResults = 10;
        eventRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
        // List events.
        Events events = eventRequest.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.");
        }
        // Create Directory API service.
        var dirService = new DirectoryService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        // Define parameters of request.
        UsersResource.ListRequest dirRequest = dirService.Users.List();
        dirRequest.Customer = "my_customer";
        dirRequest.MaxResults = 10;
        dirRequest.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
        // List users.
        IList<User> users = null;
        try
        {
            users = dirRequest.Execute().UsersValue;
            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.");
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }