Vertex AI SDK与BigQuery无效认证凭证问题求助
Colab Enterprise访问BigQuery时出现401未授权错误
在Colab Enterprise中运行《Introduction to Vertex AI SDK》的示例代码,尝试查询BigQuery数据集machine-learning-404417.Data_Beam.DryBeam,但持续收到"Unauthorized: 401"无效认证凭证错误。已确认服务账号状态正常,且为账号分配了BigQuery User角色,执行gcloud config list返回结果也无异常,但问题仍未解决。
相关代码
import pandas as pd import seaborn as sns import tensorflow as tf import google from google.cloud import bigquery from google.cloud import aiplatform from tensorflow import keras from sklearn.preprocessing import LabelBinarizer credentials, project_id = google.auth.default( scopes=["https://www.googleapis.com/auth/cloud-platform"] ) bqclient = bigquery.Client(credentials=credentials, project=project_id) query_string = """ SELECT * FROM `machine-learning-404417.Data_Beam.DryBeam` """ dataframe = bqclient.query(query_string).result().to_dataframe()
错误信息
Unauthorized: 401 POST https://bigquery.googleapis.com/bigquery/v2/projects/machine-learning-404417/jobs?prettyPrint=false: 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.
排查与解决建议
- 强制刷新Colab认证会话:在Colab中执行
from google.colab import auth; auth.authenticate_user(),重新完成认证流程,确保获取有效OAuth 2令牌。 - 确认项目绑定关系:检查当前Colab实例关联的GCP项目是否与目标BigQuery数据集所在的
machine-learning-404417项目一致;若为跨项目访问,需确保服务账号拥有跨项目访问权限。 - 验证凭证有效性:在代码中添加
print(credentials.valid)查看凭证是否有效;若无效,执行credentials.refresh(google.auth.transport.requests.Request())重新获取凭证。 - 补充必要权限:BigQuery User角色仅提供基础操作权限,需确保服务账号同时拥有
BigQuery Data Viewer角色(可针对具体数据集或表分配),保证数据访问权限充足。 - 避免凭证冲突:若代码环境中存在多种认证方式(如本地密钥文件、环境变量),明确指定使用Colab提供的凭证,防止加载无效认证信息。
内容的提问来源于stack exchange,提问作者user3542259
相关产品推荐
相关产品推荐

