Django集成Google OAuth2.0后获取Calendar事件报403权限错误如何解决
问题原因
这个403报错明确指向当前使用的OAuth凭证缺少访问Google Calendar API的授权范围,核心问题出在两个环节:OAuth授权时的scope配置错误、凭证取值错误。
解决方案
第一步:补充OAuth授权范围
你在Google Cloud控制台已经启用了Calendar API,但发起用户OAuth登录请求时,只申请了基础身份验证相关的scope(openid、邮箱、用户信息等),没有添加日历相关权限。根据你的需求添加对应scope:- 仅需要读取日程:添加
https://www.googleapis.com/auth/calendar.events.readonly - 需要读写日程:添加
https://www.googleapis.com/auth/calendar
如果使用django-allauth这类OAuth库,需要在项目settings的Google provider配置中添加上述scope。
- 仅需要读取日程:添加
第二步:修正凭证取值逻辑
你当前代码中取的是google_id_token,id_token是仅用于身份校验的JWT凭证,不能用来调用Google开放API,你需要在用户完成OAuth授权时,将返回的access_token和refresh_token存入UserAuth表,调用接口时使用access_token生成凭证。
修正后的代码示例:
from google.oauth2.credentials import Credentials from googleapiclient.discovery import build def get_events_server(request): user = User.objects.get(username=request.user) user_auth = UserAuth.objects.get(user=user) # 取存储的access_token、refresh_token,不是id_token access_token = user_auth.google_access_token refresh_token = user_auth.google_refresh_token # 该构造方式支持access_token过期后自动用refresh_token刷新,无需手动处理过期逻辑 credentials = Credentials( token=access_token, refresh_token=refresh_token, client_id="你的Google OAuth client ID", client_secret="你的Google OAuth client secret", token_uri="https://oauth2.googleapis.com/token" ) service = build('calendar', 'v3', credentials=credentials) return service
第三步:重新发起用户授权
之前已经完成授权的用户,现有凭证没有日历权限,需要引导用户重新走一遍Google OAuth登录流程,Google会弹出新的权限申请页,用户同意日历访问权限后,新生成的access_token才会包含对应scope。第四步:校验授权有效性
拿到新的access_token后,可以直接调用Google token校验接口确认返回的scope列表是否包含你配置的日历权限,确保授权配置生效。
内容的提问来源于stack exchange,提问作者Masaki93
相关产品推荐
相关产品推荐

