【发布时间】:2015-09-19 14:29:02
【问题描述】:
google api client_id 分为三种类型:
1. 网页应用
2. 服务帐号
3.安装的应用程序
我在oauth2client 的基础上成功使用了3. Installed application,但在2. Service Account 上失败了。我想通过 oauth2.0 Credentials 访问我自己的 gmail 收件箱。
import imaplib
import json
import urllib2
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build
import os
reldir = os.path.dirname(os.path.relpath(__file__))
CLIENT_SECRET_FILE = os.path.join(reldir, 'gmail_service.json')
OAUTH_SCOPE = "https://mail.google.com"
GMAIL_ADDRESS = 'my_gmail_address@gmail.com'
def jwt_oauth2():
'''
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
'''
with open(CLIENT_SECRET_FILE) as f:
data = json.loads(f.read())
private_key = data['private_key']
client_email = data['client_email']
credentials = SignedJwtAssertionCredentials(
client_email, private_key, scope=OAUTH_SCOPE)
http_auth = credentials.authorize(Http())
try:
gmail_service = build('gmail', 'v1', http=http_auth)
threads = gmail_service.users().messages().list(userId='me').execute()
except Exception as e:
return e
我遇到了与question 相同的异常。我在尝试将 sub=GMAIL_ADDRESS 添加到凭据时遇到另一个异常:AccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request.
我正在尝试找出问题,credentials 没有sub:
>>> credentials = SignedJwtAssertionCredentials(
client_email, private_key, scope=OAUTH_SCOPE)
>>> http = credentials.authorize(Http())
>>> credentials.access_token
>>> credentials.refresh(http)
>>> credentials.access_token
u'ya29.pAGJjddCXjwsiHFN6hKU1yAkdWN7xMJbks5O76Pmrpe1hW1BbgwfZifjp81aDE55ALMVgjv-yBYiyQ'
>>> gmail_service = build('gmail', 'v1', http=http)
>>> request = gmail_service.users().messages().list(userId='me')
>>> response = request.execute()
{
"error": {
"errors": [
{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
尝试使用credentials 和sub:
>>> credentials = SignedJwtAssertionCredentials(
client_email, private_key, scope=OAUTH_SCOPE, sub=GMAIL_ADDRESS)
>>> http = credentials.authorize(Http())
>>> credentials.access_token
>>> credentials.refresh(http)
AccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request.
我发现了一个类似的问题Google OAuth2 Service Account HTTP/REST Authentication,但我对node.js了解不多。任何帮助将不胜感激。
【问题讨论】:
-
服务帐号无法访问@gmail.com 邮箱。您必须使用developers.google.com/identity/protocols/OAuth2 中描述的其他受支持的 OAuth 2.0 授权方案之一。 stackoverflow.com/a/39534420/3377170 有更多详情。
标签: python python-2.7 gmail-api jwt