通过编程访问Google Sites内容遇认证问题求助
解决Google Sites服务账号认证失败问题
问题背景
- 需求:爬取自身拥有的Google Sites内容
- 已完成配置:
- 在Google Cloud控制台创建服务账号,并添加至Workspace全域委派
- 配置权限范围:
https://www.googleapis.com/auth/drive、https://www.googleapis.com/auth/sites - 自行生成JWT令牌,以
Authorization Bearer方式发送GET请求,参数包含Google Sites网址、audience设为https://sites.google.com等
- 当前问题:认证失效,请求返回Google登录页面
核心问题分析
直接手动生成JWT并作为Bearer头请求Google Sites网页端不可行——Google Sites前端页面的认证依赖Google OAuth2会话机制,而非直接接受服务账号JWT。正确做法是通过服务账号模拟Workspace授权用户,获取合法的OAuth2凭证后发起请求。
修正方案与代码实现
1. 确认前置配置正确性
- 服务账号已完成Workspace全域委派,权限范围包含
https://www.googleapis.com/auth/drive.readonly(或读写权限)、https://www.googleapis.com/auth/sites.readonly(或读写权限) - 要模拟的Workspace用户(如你自身的账号)对目标Google Sites拥有明确访问权限
2. 修正后的代码实现
import argparse from bs4 import BeautifulSoup import requests from google.oauth2 import service_account from google.auth.transport.requests import Request def get_authorized_credentials(sa_path, target_user, scopes): # 创建服务账号凭证,指定要模拟的授权用户 credentials = service_account.Credentials.from_service_account_file( sa_path, scopes=scopes, subject=target_user # 填入拥有Sites访问权限的Workspace用户邮箱 ) # 刷新凭证获取有效访问令牌 credentials.refresh(Request()) return credentials def make_authenticated_request(credentials, url): headers = { "Authorization": f"Bearer {credentials.token}" } response = requests.get(url, headers=headers) response.raise_for_status() html = response.content.decode("utf-8") clean_html = remove_tags(html) print(clean_html) def remove_tags(html): soup = BeautifulSoup(html, "html.parser") for data in soup(['style', 'script']): data.decompose() return ' '.join(soup.stripped_strings) if __name__ == "__main__": parser = argparse.ArgumentParser(description="爬取Google Sites内容") parser.add_argument("host", help="目标Google Sites网址,示例:https://sites.google.com/your-domain/your-site") parser.add_argument("sa_path", help="服务账号JSON密钥文件路径") parser.add_argument("target_user", help="要模拟的Workspace用户邮箱(需拥有Sites访问权限)") args = parser.parse_args() # 定义所需权限范围(按需选择只读/读写) scopes = [ "https://www.googleapis.com/auth/drive.readonly", "https://www.googleapis.com/auth/sites.readonly" ] print("获取认证凭证...") credentials = get_authorized_credentials(args.sa_path, args.target_user, scopes) print("发起请求...") make_authenticated_request(credentials, args.host)
3. 关键修正说明
- 替换手动JWT生成逻辑:使用Google官方
google-auth库处理凭证,自动完成令牌生成、刷新与有效期管理 - 添加用户模拟:服务账号本身无Workspace资源访问权,必须通过
subject参数模拟拥有权限的用户 - 精简权限范围:根据实际需求选择只读或读写权限,避免过度授权
4. 运行命令示例
python your_script.py "https://sites.google.com/your-domain/your-site" "./service-account-key.json" "your-workspace-email@your-domain.com"
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

