Google服务帐户身份验证Python:401请求具有无效的身份验证凭据

huangapple go评论69阅读模式
英文:

Google service account authentication Python: 401 Request had invalid authentication credentials

问题

I am writing a script that needs to connect to the Google API and download some emails. This script will run on a server, so I need to make sure that it does not require user interaction when authenticating.

文档建议在服务器之间的应用程序中使用服务帐户。我按照文档中的教程操作,但返回了401错误。

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from typing import List, Dict
import logging

logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
KEYWORD = "LinkedIn"

def login() -> Credentials:
    try:
        credentials = Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
        return credentials
    except Exception as ex:
        logging.error(f"-----ERROR-----login: {ex}")

def get_unread_messages(credentials) -> List[Dict]:
    try:
        service = build('gmail', 'v1', credentials=credentials)
        result = service.users().messages().list(userId='me', labelIds=["INBOX", "UNREAD"]).execute()
        message_ids = result.get('messages')
        unread_messages = [service.users().messages().get(userId='me', id=msg['id']).execute() for msg in message_ids]
        return unread_messages
    except Exception as ex:
        logging.error(f"-----ERROR-----get_unread_messages:{ex}")

credentials = login()
get_unread_messages(credentials)

错误信息

------ERROR-----get_unread_messages:<HttpError 401 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&amp;labelIds=UNREAD&amp;alt=json returned "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.". Details: "[{'message': 'Invalid Credentials', 'domain': 'global', 'reason': 'authError', 'location': 'Authorization', 'locationType': 'header'}]">
英文:

I am writing a script that needs to connect to the Google API and download some emails. This script will run in a server, so I need to make sure that it does not require user interaction when authenticating.

The documentation suggest to use a service account for server-to-server applications. I followed the tutorial in the docs, but it comes back with 401.

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from typing import List, Dict
import logging


logging.basicConfig(format=&#39;%(asctime)s - %(message)s&#39;, level=logging.INFO)


SCOPES = [&#39;https://www.googleapis.com/auth/gmail.readonly&#39;]
KEYWORD = &quot;LinkedIn&quot;


def login() -&gt; Credentials:
    try:
        credentials = Credentials.from_service_account_file(&#39;credentials.json&#39;, scopes=SCOPES)
        return credentials

    except Exception as ex:
        logging.error(f&quot;-----ERROR-----login: {ex}&quot;)
        



def get_unread_messages(credentials) -&gt; List[Dict]:
    try:

        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=credentials)

        result = service.users().messages().list(userId=&#39;me&#39;, labelIds=[&quot;INBOX&quot;, &quot;UNREAD&quot;]).execute()

        message_ids = result.get(&#39;messages&#39;)
        unread_messages = [service.users().messages().get(userId=&#39;me&#39;, id=msg[&#39;id&#39;]).execute() for msg in message_ids]

        return unread_messages

    except Exception as ex:
        logging.error(f&quot;-----ERROR-----get_unread_messages:{ex}&quot;)

credentials = login()
get_unread_messages(credentials )

**
Error message**

------ERROR-----get_unread_messages:&lt;HttpError 401 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&amp;labelIds=UNREAD&amp;alt=json returned &quot;Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.&quot;. Details: &quot;[{&#39;message&#39;: &#39;Invalid Credentials&#39;, &#39;domain&#39;: &#39;global&#39;, &#39;reason&#39;: &#39;authError&#39;, &#39;location&#39;: &#39;Authorization&#39;, &#39;locationType&#39;: &#39;header&#39;}]&quot;&gt;

答案1

得分: 0

服务账户授权仅适用于配置了域范围委托并在您的代码中添加了用户模拟的Google Workspace域帐户。

对于标准Gmail帐户,您需要使用OAuth2进行一次用户授权并存储刷新令牌。

英文:

service account authorization only works with google workspace domain accounts after you have configured domain wide deligation and added a user impersonation to you code.

for standard Gmail accounts you need to use Oauth2 and authorize the user once and store the refresh token

huangapple
  • 本文由 发表于 2023年4月19日 18:32:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定