我最近一直致力于从 python 脚本访问 gmail API。
由于脚本需要在服务器上运行,而无需任何形式的 Web 浏览器,因此我必须实现设备 OAuth 流程,详情请参阅 https://developers.google.com/accounts/docs/OAuth2ForDevices
一切进展顺利,因为我一直在“配置文件”范围内进行测试,所以我已经按预期获得了访问 token 。
但是,为了切换到我的脚本所需的实际 token ,因为我需要获得授权才能写入用户的电子邮件,我尝试在 www.googleapis.com/范围内运行我的脚本auth/gmail.compose
,它返回以下内容:
{u'error_uri': u'code.google.com/apis/accounts/docs/OAuth2.html', u'error_description': u'Not authorized to request the scopes: [www.googleapis.com/auth/gmail.compose]', u'error': u'invalid_scope'}
此时我很好奇,并尝试了各种范围,对我来说似乎相当随意,哪些可以工作,哪些不能工作。
工作:
www.googleapis.com/auth/calendar
www.google.com/m8/feeds
不工作:
mail.google.com/
www.googleapis.com/auth/gmail.compose
www.googleapis.com/auth/gmail.readonly
www.googleapis.com/auth/gmail.modify
www.googleapis.com/auth/contacts.readonly
我已将代码上传到 https://gist.github.com/Hanse00/3a861430b1543599b3ed任何有兴趣的人都可以看看。
Gmail API 确实已在项目控制台中启用。
如果有人知道为什么会发生这种情况,我很高兴收到您的来信!
注意:我必须编辑范围,因为它们算作链接,而且我的声誉不够高,无法发布全部内容。我尝试过的范围实际上是正确的。
最佳答案
设备流的 Oauth2 安全性较低,对于某些不太敏感的 API 来说是可以/允许的,但并非全部。 Gmail API 不允许使用它。
您可以让您的服务器实现 Web 服务器流程(如果您可以在其上运行 http 服务器),然后您的客户端将使用您可以检索+存储的正确 token 重定向回那里: https://developers.google.com/accounts/docs/OAuth2WebServer
关于python - 无权请求范围 - Google OAuth2 for devices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28855393/