如何配置Dex从GCP获取令牌,访问Artifact Registry等服务
通过Dex配置GCP OIDC认证解决镜像拉取与服务访问问题
核心需求场景
- 在Hetzner Cloud的VPS上,通过docker-compose拉取GCP Artifact Registry中的Docker镜像并启动Web应用
- 应用内部完成GCP认证,访问Cloud Storage(GCS)与Vertex AI服务
现有架构组件:docker-compose.yml、nginx.conf、dex/config.yaml配置文件,通过smart-start.sh脚本启动服务(而非直接执行docker compose up -d)
Dex的GCP OIDC认证配置方案
1. GCP控制台创建OAuth客户端凭据
- 进入GCP控制台「API和服务」→「凭据」页面
- 创建「OAuth客户端ID」,应用类型选「Web应用」
- 填写授权回调URL:
http://<你的VPS域名/IP>:<Dex端口>/callback(比如http://1.2.3.4:5556/callback) - 保存生成的客户端ID和客户端密钥
2. 配置Dex的config.yaml
在dex/config.yaml中添加GCP作为认证源,示例配置如下:
issuer: http://<你的VPS域名/IP>:<Dex端口>/dex storage: type: sqlite3 config: file: /var/dex/dex.db web: http: 0.0.0.0:5556 oauth2: skipApprovalScreen: true connectors: - type: google id: google name: Google config: clientID: "<你的GCP OAuth客户端ID>" clientSecret: "<你的GCP OAuth客户端密钥>" redirectURI: "http://<你的VPS域名/IP>:<Dex端口>/callback" # 按需添加权限范围,覆盖镜像拉取、GCS、Vertex AI需求 scopes: - "openid" - "email" - "profile" - "https://www.googleapis.com/auth/cloud-platform" - "https://www.googleapis.com/auth/devstorage.read_write" - "https://www.googleapis.com/auth/aiplatform"
提示:如果仅需拉取镜像,可简化
scopes为openid、https://www.googleapis.com/auth/cloud-platform
3. 配置docker-compose镜像拉取认证
让Docker通过Dex获取的令牌访问Artifact Registry:
- 修改docker-compose.yml,指定凭证路径:
services: your-web-app: image: us-central1-docker.pkg.dev/<GCP项目ID>/<仓库名>/<镜像名>:<标签> pull_policy: always environment: - GOOGLE_APPLICATION_CREDENTIALS=/tmp/gcp-token.json volumes: - ./dex-gcp-token:/tmp/gcp-token.json # 其他应用配置...
- 更新
smart-start.sh,添加令牌获取逻辑(自动化场景建议用设备授权流程避免手动交互):
#!/bin/bash # 替换为实际的Dex客户端信息和授权码 curl -X POST http://<你的VPS域名/IP>:5556/token \ -d "grant_type=authorization_code" \ -d "client_id=<你的Dex客户端ID>" \ -d "client_secret=<你的Dex客户端密钥>" \ -d "code=<OAuth授权码>" \ -d "redirect_uri=http://localhost:8080/callback" > ./dex-gcp-token # 启动服务 docker compose up -d
4. 应用内部GCP服务访问配置
应用可直接使用Dex获取的令牌完成认证:
- 读取
GOOGLE_APPLICATION_CREDENTIALS指定的令牌文件,自动处理凭证刷新 - Python示例:
import google.auth from google.auth.transport.requests import Request from google.cloud import storage # 加载Dex生成的令牌凭证 credentials, project_id = google.auth.load_credentials_from_file('/tmp/gcp-token.json') if credentials.expired and credentials.refresh_token: credentials.refresh(Request()) # 访问Cloud Storage storage_client = storage.Client(credentials=credentials, project=project_id) buckets = list(storage_client.list_buckets())
内容的提问来源于stack exchange,提问作者Jose A
相关产品推荐
相关产品推荐

