首页 > 解决方案 > 尝试创建新事件时出现身份验证范围不足错误

问题描述

我想用 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 [

标签: c#google-apigoogle-oauthgoogle-calendar-apigoogle-api-dotnet-client

解决方案


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

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

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

在此处输入图像描述

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

笔记:

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

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

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

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

推荐阅读