Python3使用PyDrive时如何隐藏client_secrets.json配置文件
PyDrive隐藏client_secrets.json的可行方案
- 将配置写入环境变量,动态生成临时文件后销毁
你可以把client_secrets.json的所有字段提前存入系统环境变量或加密存储区,PyDrive初始化前读取配置生成临时json文件,认证完成后立刻删除该文件即可,参考代码如下:
import os import json from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive # 从环境变量读取配置字段 client_config = { "web": { "client_id": os.getenv("GDRIVE_CLIENT_ID"), "client_secret": os.getenv("GDRIVE_CLIENT_SECRET"), "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"] } } # 生成临时配置文件 temp_config_path = "temp_client_secrets.json" with open(temp_config_path, "w", encoding="utf-8") as f: json.dump(client_config, f) # 初始化认证 gauth = GoogleAuth() gauth.LoadClientConfigFile(temp_config_path) # 此处走你自己的认证流程,例如本地网页认证、加载已有凭证等 gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) # 认证完成后立即删除临时文件 os.remove(temp_config_path)
- 直接传入配置字典,跳过实体文件读取*(最推荐方案)*
PyDrive的GoogleAuth对象原生支持直接传入配置字典,完全不需要生成实体的client_secrets.json文件,从根源避免文件被普通用户访问,参考代码如下:
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() # 直接赋值配置字典,无需任何外部配置文件 gauth.client_config = { "client_id": "替换为你的client_id", "client_secret": "替换为你的client_secret", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "revoke_uri": "https://oauth2.googleapis.com/revoke", "redirect_uri": "urn:ietf:wg:oauth:2.0:oob" } # 后续正常执行认证流程即可 gauth.LocalWebserverAuth() drive = GoogleDrive(gauth)
如果担心client_id和client_secret明文写在代码中被反编译,可以将两个字段加密存储,程序运行时解密后再赋值到配置字典即可。
- 修改文件系统权限限制访问
如果你确实需要保留实体的client_secrets.json文件,可以在部署时调整文件权限,仅为程序运行的账号授予读权限,普通用户无任何访问权限:- Linux/macOS环境下执行命令
chmod 600 client_secrets.json即可 - Windows环境下在文件的安全属性面板中,移除所有普通用户组的访问权限
- Linux/macOS环境下执行命令
内容的提问来源于stack exchange,提问作者BeyondComprehension
相关产品推荐
相关产品推荐

