You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Search Console授权报错,现有服务账号凭据如何适配鉴权

问题原因

你当前使用的是服务账号类型的凭据,而Credentials.from_authorized_user_info方法仅适用于普通用户OAuth授权生成的凭据,两者结构完全不兼容,因此会抛出缺少client_secret、refresh_token字段的错误。

适配现有凭据的解决方案

直接使用服务账号对应的凭证加载类即可,不需要修改你现有的凭据内容,修改后的代码如下:

# 替换原来的Credentials导入,使用服务账号专用的凭证类
from google.oauth2 import service_account
from googleapiclient import discovery

class GoogleSearchConsoleApiClient():
    SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
 
    def __init__(self):
        pass

    def get_sites(self, creds):
        try:
            service = discovery.build('searchconsole', 'v1', credentials=creds, cache_discovery=False)
            site_list = service.sites().list().execute()
            print(site_list)
        except Exception as e:
            raise e
        # 修复原代码的bug:原代码返回未定义的url变量,改为返回站点列表
        return site_list

    def execute(self):
        service_account_info = {
            "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "client_email": "XXXXX",
            "client_id": "XXXXX",
            "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/XXXX",
            "owner": "XXX",
            "private_key": "XXX",
            "private_key_id": "XX",
            "project_id": "XXX",
            "token_uri": "https://oauth2.googleapis.com/token",
            "type": "service_account"
        }
        # 使用服务账号方法加载凭据
        credentials = service_account.Credentials.from_service_account_info(
            service_account_info, 
            scopes=self.SCOPES
        )
        sites_list = self.get_sites(credentials)
        return sites_list


if __name__ == '__main__':
    a = GoogleSearchConsoleApiClient().execute()
    print(a)
注意事项
  • 你需要提前将凭据中的client_email对应的服务账号邮箱,添加到Google Search Console对应站点的权限列表中,授权至少只读权限,否则调用API会返回403无权限错误。
  • 你当前使用的Python2.7已经停止维护,新版google-auth库不再支持Python2.7,如果运行时报库版本相关错误,可安装兼容Python2.7的最后版本:pip install google-auth==1.35.0 google-api-python-client==1.12.11。

内容的提问来源于stack exchange,提问作者Avenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:45:05