使用Calendar scope调用谷歌日历API添加事件仍提示认证范围不足
问题原因
- 本地缓存的授权令牌权限未更新:如果此前使用过只读日历权限运行过程序,生成的
token.json文件会缓存低权限令牌,即便后续修改了权限范围,程序默认读取旧缓存,不会重新发起授权,导致实际令牌仅有读取权限。 - 目标日历权限配置错误:你操作的
TestAGarcia日历如果是共享日历,当前授权的谷歌账号仅被分配了只读权限,应用即便申请了修改权限也无法执行写入操作。 - 代码参数违规:谷歌日历的事件ID、创建者信息由服务端自动生成,代码中手动指定
miEventoNuevo.Id和CreatorData会触发服务端校验规则,容易被误判为权限异常。同时代码未配置事件的起止时间,属于必填参数缺失,也会触发服务端报错。
解决步骤
- 清理旧授权缓存:删除程序运行目录下的
token.json文件夹,重新运行程序触发授权流程,确认授权提示的权限包含日历编辑权限。 - 校验目标日历权限:登录谷歌日历网页端,打开
TestAGarcia日历的设置页面,在共享设置中确认当前授权账号拥有「修改事件」及以上权限,不要设置为仅可读权限。 - 修正代码逻辑:删除手动赋值事件ID、创建者信息的代码,补充必填的起止时间参数,参考代码如下:
private void ucBtnCrearEvento_Click(object sender, RoutedEventArgs e) { CalendarService miCalendarService = GetCalendarService(); IEnumerable<CalendarListEntry> misCalendarios = miCalendarService.CalendarList.List().Execute().Items; CalendarListEntry miCalendario = misCalendarios.FirstOrDefault(x => string.CompareOrdinal(x.Summary, "TestAGarcia") == 0); Event miEventoNuevo = new Event(); miEventoNuevo.Summary = "Esto es Summary 01"; miEventoNuevo.Description = "Esto es el description"; // 补充必填的起止时间参数,时区替换为实际使用的时区 miEventoNuevo.Start = new EventDateTime() { DateTime = DateTime.Now.AddHours(1), TimeZone = "Europe/Madrid" }; miEventoNuevo.End = new EventDateTime() { DateTime = DateTime.Now.AddHours(2), TimeZone = "Europe/Madrid" }; miCalendarService.Events.Insert(miEventoNuevo, miCalendario.Id).Execute(); }
内容的提问来源于stack exchange,提问作者Álvaro García
相关产品推荐
相关产品推荐

