如何获取Google Classroom当前登录用户ID以与login_hint对比?
获取Google Classroom当前登录用户ID的方法
核心实现方式
在Google Classroom插件的Python开发场景中,你可以通过以下方式获取当前登录用户ID,用于和login_hint参数比对:
通过Google People API直接获取
当用户完成OAuth2授权后,利用已有的用户凭据调用People API的people.get接口,指定获取用户的元数据信息,其中就包含用户的Google ID(即Classroom中的登录用户ID)。示例Python代码:
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # 假设已通过OAuth流程获取到有效的用户凭据credentials people_service = build('people', 'v1', credentials=credentials) user_profile = people_service.people().get( resourceName='people/me', personFields='metadata' ).execute() current_user_id = user_profile['metadata']['source']['id']OAuth授权范围要求
确保你的应用OAuth授权范围包含https://www.googleapis.com/auth/userinfo.profile或https://www.googleapis.com/auth/classroom.profile.emails,否则调用People API会因权限不足报错。
与login_hint的比对逻辑
获取到current_user_id后,直接和请求中的login_hint参数做字符串相等校验:
- 若两者不匹配,渲染谷歌品牌登录按钮;
- 若用户未登录(凭据无效/不存在),直接显示登录按钮即可,无需执行比对。
内容的提问来源于stack exchange,提问作者Mark Zamoyta
相关产品推荐
相关产品推荐

