【问题标题】:failedPrecondition when using google Oauth2 Service AccountfailedPrecondition 使用 google Oauth2 服务帐户时
【发布时间】: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"
 }
}

尝试使用credentialssub

>>> 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了解不多。任何帮助将不胜感激。

【问题讨论】:

标签: python python-2.7 gmail-api jwt


【解决方案1】:

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

假设,使用您的服务帐户,您想获取用户 user@domain.com 的详细信息,子字段应填充为:

sub: user@domain.com

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

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 2017-01-23
    • 2013-08-21
    • 2019-01-23
    • 2012-11-06
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多