Google Classroom API权限范围不足:创建courseWork报错求解决方案
解决Google Classroom创建CourseWork时的权限范围不足错误
这个坑我踩过!你遇到的Request has insufficient authentication scopes错误,本质是权限范围选得不对,再加上OAuth缓存了旧权限导致的,按下面几步就能解决:
1. 替换为正确的权限范围
你现在用的https://www.googleapis.com/auth/classroom.coursework.students是给学生账号用的(用来查看自己的作业),而创建作业需要的是老师身份的权限范围。根据需求选一个:
- 如果只是创建自己作为老师的作业,用
https://www.googleapis.com/auth/classroom.coursework.me(最小权限原则,推荐) - 如果需要管理学生的作业(比如批改、创建),用
https://www.googleapis.com/auth/classroom.coursework.students
2. 删除旧的授权缓存文件
OAuth会把之前授权的权限存在credentials.json里,就算你改了代码里的scope,旧缓存还是会生效。所以一定要把这个文件删掉,等下重新运行程序时会重新弹出授权页面,获取新的权限。
3. 确认你的账号是课程的老师/所有者
如果你的Google账号在目标课程里只是学生或助教身份,就算权限范围对了也会报错,务必确认账号的角色是课程的老师或者所有者。
修改后的完整代码
from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools store = file.Storage('credentials.json') creds = store.get() # 替换为老师权限的scope SCOPES = 'https://www.googleapis.com/auth/classroom.coursework.me' if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('classroom', 'v1', http=creds.authorize(Http())) courseWork = { 'title': 'Ant colonies', 'description': 'Read the article about ant colonies and complete the quiz.', 'materials': [ {'link': { 'url': 'http://example.com/ant-colonies' }}, {'link': { 'url': 'http://example.com/ant-quiz' }} ], 'workType': 'ASSIGNMENT', 'state': 'PUBLISHED', } courseWork = service.courses().courseWork().create(courseId='105332016379', body=courseWork).execute() print('Assignment created with ID {0}'.format(courseWork.get('id')))
做完上面这几步,重新运行程序,授权新的权限,应该就能成功创建作业了!
内容的提问来源于stack exchange,提问作者Pradip Dhakal
相关产品推荐
相关产品推荐

