使用谷歌Oauth2服务帐户时失败的前提条件

时间:2015-07-02 07:28:17

标签: python python-2.7 gmail-api jwt

有三种类型的google api client_id:
 1. Web应用程序
 2.服务帐户
 3.已安装的应用程序

我已成功使用> A=outer(outer(1:10,1:10,"+"),1:10,"+") > A[1,2,3] [1] 6 > A[4,8,9] [1] 21 基于oauth2client,但在3. Installed application上失败了。我想用oauth2.0 2. Service Account访问我自己的gmail收件箱。

Credentials

我得到的异常与question相同。尝试将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 添加到凭据中时遇到另一个例外:
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

我发现了一个类似的问题Google OAuth2 Service Account HTTP/REST Authentication,但我对>>> 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. 了解不多。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:-1)

您应该使用您指定要模拟的帐户的子字段。

说,使用您的服务帐户,您希望获得用户user@domain.com的详细信息,子字段应填充为:

sub: user@domain.com

您还应确保已向域中的用户授予服务帐户访问权限。 请参阅 - https://developers.google.com/drive/web/delegation