简体   繁体   中英

Google Calendar API - Create/Insert/Add event - C# - error 403

I'm trying to create a C# tool to manipulate my Google Calendar. The tool is receives events from API successfully, but when trying to create an event I get the error:

Google.GoogleApiException: 'Google.Apis.Requests.RequestError
Insufficient Permission: Request had insufficient authentication scopes. [403]
Errors [
    Message[Insufficient Permission: Request had insufficient authentication scopes.] Location[ - ] Reason[insufficientPermissions] Domain[global]
]

I have 2 buttons: one for creating event and one button for showing the upcoming events. Please observe that I tried 3 different methods to add an event, all with the same error result.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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;

namespace GoogleCalendarsAssistant
{
    public partial class form_GoogleCalendarsAssistant : Form
    {
        public static class g
        {
            public static string[] Scopes = { CalendarService.Scope.Calendar };
            public static string ApplicationName = "GoogleCalendarsAssistant";

            public static UserCredential credential;
        }
        public string newline = "\r\n";
        public string tab     = "    ";


        public form_GoogleCalendarsAssistant()
        {
            InitializeComponent();
        }


        private void btn_addEvent_Click(object sender, EventArgs e)
        {
            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
                string credPath = "token.json";
                g.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    g.Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
                //tb_general.Text += newline + "Credential file saved to: " + credPath;
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = g.credential,
                ApplicationName = g.ApplicationName,
            });

            // Define parameters of request.
            Event addEvent_body = new Event();

            addEvent_body.Summary = "test summary";
            addEvent_body.Location = "test location";
            addEvent_body.Description = "test description";
            addEvent_body.Start = new EventDateTime()
            {
                DateTime = new DateTime(2019, 3, 7, 14, 0, 0),
                TimeZone = "Romania/Bucharest"
            };
            addEvent_body.End = new EventDateTime()
            {
                DateTime = new DateTime(2019, 3, 7, 15, 0, 0),
                TimeZone = "Romania/Bucharest"
            };
            addEvent_body.Attendees = new List<EventAttendee>()
            {
                new EventAttendee() {Email = "john@myjob.com"}
            };

            // Add event
            //method 1
            Event addEvent = service.Events.Insert(addEvent_body, "primary").Execute();

            //method 2
            //EventsResource.InsertRequest addEventResource = service.Events.Insert(addevent_body, "primary");
            //addEventResource.Execute();

            //method 3
            //EventsResource.InsertRequest request = service.Events.Insert(addevent_body, "primary");
            //request.Execute();
        }

        private void btn_upcoming_Click(object sender, EventArgs e)
        {
            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
                string credPath = "token.json";
                g.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    g.Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
                //tb_general.Text += newline + "Credential file saved to: " + credPath;
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = g.credential,
                ApplicationName = g.ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 30;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            //Console.WriteLine("Upcoming events:");
            tb_general.Text = "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);
                    tb_general.Text += newline + tab + eventItem.Summary + when;
                }
            }
            else
            {
                //Console.WriteLine("No upcoming events found.");
                tb_general.Text = newline + "No upcoming events found.";
            }
            //Console.Read();
        }


    }
}

So... I found the problem: when the app starts for the first time, Google API creates a token.json file based on the desired Scopes. In my case, I first used "CalendarReadOnly" and then I edited this in "Calendar" in order to be able to create and delet events. So I just deleted the token.json and launched the app again and a new token.json was received with the "Calendar" scope. Also, I gave up setting the timezone because of the error 400, but it's optional anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM