尝试创建新事件时身份验证范围不足错误

时间:2021-02-01 12:45:38

标签: c# google-api google-oauth google-calendar-api google-api-dotnet-client

我想用 C# 在 Google 日历中创建一个事件。我正处于编程的第一阶段,但我想尝试解决这个问题。

代码:

private void GoogleAPI_Add_events()
    {
        UserCredential credential;

        using (var stream =
            new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
        {
            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.
            string credPath = "token.json";
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // 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 = 8;
        request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
        var ev = new Event();
        EventDateTime start = new EventDateTime();
        start.DateTime = new DateTime(2021, 3, 11, 10, 0, 0);

        EventDateTime end = new EventDateTime();
        end.DateTime = new DateTime(2021, 3, 15, 10, 0, 0);
        ev.Start = start;
        ev.End = end;
        ev.Summary = "New Event";
        ev.Description = "Description...";

        var calendarId = "primary";
        Event recurringEvent = service.Events.Insert(ev, calendarId).Execute();
        MessageBox.Show("New evento creato");
    }

我收到此错误:

<块引用>

Google.GoogleApiException: 'Google.Apis.Requests.RequestError Request had insufficient authentication scopes. [403] Errors [

1 个答案:

答案 0 :(得分:2)

<块引用>

请求的身份验证范围不足。

基本上意味着您当前对您的应用程序进行身份验证的用户没有授予您执行您正在尝试执行的操作所需的权限。

您正在尝试使用需要以下范围之一的 Events.insert 方法。

enter image description here

您还没有以 Scope 的形式发布您要发送的内容,但我猜这不是其中之一。

注意:

请记住,当您更改范围时,您需要更改“用户”文本或删除存储在 credPath 中的用户的凭据文件,否则它不会为您的应用程序请求新的授权。

在下面的代码中,术语“用户”表示您正在登录的用户,如果您已经使用该用户登录,则该用户的凭据由 FileDataStore 存储在 credsPath 目录中,您应该有一个目录称为 token.json。

要么将“user”更改为其他字符串,例如“user1”,要么进入该目录并删除该文件。

 credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;