google-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGoogle Authentication for Node.js & Python
Node.js 和 Python 中的 Google 认证
Libraries
相关库
Node.js
Node.js
- — core auth library (OAuth2Client, GoogleAuth, JWT, Compute, Impersonated)
google-auth-library - — Google API client (wraps google-auth-library)
googleapis
bash
npm install google-auth-library
npm install googleapis- — 核心认证库(包含OAuth2Client、GoogleAuth、JWT、Compute、Impersonated)
google-auth-library - — Google API客户端(封装了google-auth-library)
googleapis
bash
npm install google-auth-library
npm install googleapisPython
Python
- — core auth library (google.oauth2, google.auth, credentials, transport)
google-auth - — OAuth 2.0 user-credential flow helpers (Flow, InstalledAppFlow)
google-auth-oauthlib - — Google API client (wraps google-auth)
google-api-python-client
bash
pip install google-auth
pip install google-auth-oauthlib
pip install google-api-python-client- — 核心认证库(包含google.oauth2、google.auth、credentials、transport)
google-auth - — OAuth 2.0用户凭证流程工具(包含Flow、InstalledAppFlow)
google-auth-oauthlib - — Google API客户端(封装了google-auth)
google-api-python-client
bash
pip install google-auth
pip install google-auth-oauthlib
pip install google-api-python-clientAuthentication Methods Overview
认证方法概览
| Method | Use Case | Node.js Key Class | Python Key Module / Class |
|---|---|---|---|
| ADC | Same identity for all users, server-to-server | | |
| OAuth 2.0 | Actions on behalf of end users | | |
| Sign In with Google (GIS) | User sign-in/sign-up on websites | GIS JS SDK + | GIS JS SDK + |
| JWT / Service Account | Server-to-server, single identity | | |
| API Key | Public data, no user context | | passed to |
| Compute | On GCP with attached service account | | |
| Workload Identity Federation | AWS/Azure/OIDC → GCP without SA keys | | |
| 认证方法 | 适用场景 | Node.js核心类 | Python核心模块/类 |
|---|---|---|---|
| ADC | 所有用户使用同一身份,服务器到服务器通信 | | |
| OAuth 2.0 | 代表终端用户执行操作 | | |
| Sign In with Google (GIS) | 网站用户登录/注册 | GIS JS SDK + | GIS JS SDK + |
| JWT / 服务账号 | 服务器到服务器通信,单一身份 | | |
| API密钥 | 公开数据访问,无用户上下文 | | 传入 |
| Compute | 在GCP上使用附加服务账号 | | |
| Workload Identity Federation | AWS/Azure/OIDC → GCP,无需服务账号密钥 | | |
Quick Patterns
快速实现示例
1. Application Default Credentials (ADC)
1. Application Default Credentials (ADC)
Node.js
js
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const res = await client.fetch('https://dns.googleapis.com/dns/v1/projects/...');Python
python
import google.auth
import google.auth.transport.requests
credentials, project = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
request = google.auth.transport.requests.Request()
credentials.refresh(request)ADC search order: attached service account → file → env var.
gcloud auth application-default loginGOOGLE_APPLICATION_CREDENTIALSFor detailed ADC setup and service account usage, see references/adc-and-service-accounts.md.
Node.js
js
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const res = await client.fetch('https://dns.googleapis.com/dns/v1/projects/...');Python
python
import google.auth
import google.auth.transport.requests
credentials, project = google.auth.default(
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
request = google.auth.transport.requests.Request()
credentials.refresh(request)ADC的查找顺序:附加的服务账号 → 生成的文件 → 环境变量。
gcloud auth application-default loginGOOGLE_APPLICATION_CREDENTIALS如需了解ADC的详细配置和服务账号使用方法,请查看 references/adc-and-service-accounts.md。
2. OAuth 2.0 Web Server Flow
2. OAuth 2.0 Web服务器流程
Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: REDIRECT_URI
});
const authUrl = client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/userinfo.profile'],
state: crypto.randomBytes(32).toString('hex'),
include_granted_scopes: true
});
// After redirect: exchange code for tokens
const {tokens} = await client.getToken(code);
client.setCredentials(tokens);Python
python
from google_auth_oauthlib.flow import Flow
flow = Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/userinfo.profile'],
redirect_uri=REDIRECT_URI
)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: REDIRECT_URI
});
const authUrl = client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/userinfo.profile'],
state: crypto.randomBytes(32).toString('hex'),
include_granted_scopes: true
});
// 重定向后:交换授权码获取令牌
const {tokens} = await client.getToken(code);
client.setCredentials(tokens);Python
python
from google_auth_oauthlib.flow import Flow
flow = Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/userinfo.profile'],
redirect_uri=REDIRECT_URI
)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)After redirect: exchange code for tokens
重定向后:交换授权码获取令牌
flow.fetch_token(code=code)
credentials = flow.credentials
`refresh_token` is only returned on the first authorization. Use `prompt: 'consent'` (Node.js) or `prompt='consent'` (Python) to force re-consent.
For the complete OAuth 2.0 flow (parameters, token exchange, refresh, revocation, incremental auth), see [references/oauth2-web-server.md](references/oauth2-web-server.md).flow.fetch_token(code=code)
credentials = flow.credentials
`refresh_token`仅在首次授权时返回。使用`prompt: 'consent'`(Node.js)或`prompt='consent'`(Python)强制用户重新授权。
如需完整的OAuth 2.0流程(参数、令牌交换、刷新、撤销、增量授权),请查看 [references/oauth2-web-server.md](references/oauth2-web-server.md)。3. Sign In with Google — ID Token Verification
3. Sign In with Google — ID令牌验证
Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client();
const ticket = await client.verifyIdToken({
idToken: token,
audience: WEB_CLIENT_ID,
});
const payload = ticket.getPayload();
const userId = payload['sub'];
const email = payload['email'];
const name = payload['name'];
const picture = payload['picture'];Python
python
from google.oauth2 import id_token
from google.auth.transport import requests
request = requests.Request()
payload = id_token.verify_oauth2_token(
token,
request,
WEB_CLIENT_ID
)
user_id = payload['sub']
email = payload['email']
name = payload.get('name', '')
picture = payload.get('picture')Verification checks: JWT signature, , , (accounts.google.com).
audexpissFor GIS integration, CSRF protection, and hosted domain validation, see references/sign-in-with-google.md.
Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client();
const ticket = await client.verifyIdToken({
idToken: token,
audience: WEB_CLIENT_ID,
});
const payload = ticket.getPayload();
const userId = payload['sub'];
const email = payload['email'];
const name = payload['name'];
const picture = payload['picture'];Python
python
from google.oauth2 import id_token
from google.auth.transport import requests
request = requests.Request()
payload = id_token.verify_oauth2_token(
token,
request,
WEB_CLIENT_ID
)
user_id = payload['sub']
email = payload['email']
name = payload.get('name', '')
picture = payload.get('picture')验证检查项:JWT签名、、、(accounts.google.com)。
audexpiss如需了解GIS集成、CSRF防护及托管域名验证,请查看 references/sign-in-with-google.md。
4. JWT / Service Account
4. JWT / 服务账号
Node.js
js
const {JWT} = require('google-auth-library');
const keys = require('./service-account-key.json');
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const res = await client.fetch(url);Python
python
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
'service-account-key.json',
scopes=['https://www.googleapis.com/auth/cloud-platform']
)Node.js
js
const {JWT} = require('google-auth-library');
const keys = require('./service-account-key.json');
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const res = await client.fetch(url);Python
python
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
'service-account-key.json',
scopes=['https://www.googleapis.com/auth/cloud-platform']
)Or from a dict already loaded into memory:
或者从已加载到内存的字典中创建:
credentials = service_account.Credentials.from_service_account_info(
info,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
undefinedcredentials = service_account.Credentials.from_service_account_info(
info,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
undefined5. API Key
5. API密钥
Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client({ apiKey: 'my-api-key' });
// Or via GoogleAuth:
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth({
clientOptions: { apiKey: 'my-api-key' }
});Python
python
from googleapiclient.discovery import build
service = build('customsearch', 'v1', developerKey='my-api-key')Node.js
js
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client({ apiKey: 'my-api-key' });
// 或者通过GoogleAuth:
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth({
clientOptions: { apiKey: 'my-api-key' }
});Python
python
from googleapiclient.discovery import build
service = build('customsearch', 'v1', developerKey='my-api-key')6. Token Refresh
6. 令牌刷新
Node.js
js
client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// Store refresh_token — only sent on first auth
}
console.log(tokens.access_token);
});Python
python
from google.auth.transport.requests import Request
if credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
# credentials.token is the new access token
# credentials.expiry is the new expiration datetimeNode.js
js
client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// 存储refresh_token — 仅在首次授权时返回
}
console.log(tokens.access_token);
});Python
python
from google.auth.transport.requests import Request
if credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
# credentials.token 是新的访问令牌
# credentials.expiry 是新的过期时间Security Best Practices
安全最佳实践
- Never expose or service account keys in client-side code
client_secret - Always validate parameter to prevent CSRF in OAuth flows
state - Use (not
sub) as the unique user identifier from Google ID tokensemail - Store securely; it's only returned on first authorization
refresh_token - Validate external credential configurations before use (check ,
token_urlpoint to googleapis.com)service_account_impersonation_url - Prefer Workload Identity Federation over service account keys for non-GCP environments
- For GIS: verify with double-submit-cookie pattern
g_csrf_token - Python-specific: reuse a single instance across verifications for connection pooling; do not create a new one per call in hot paths
google.auth.transport.requests.Request()
- 切勿在客户端代码中暴露或服务账号密钥
client_secret - 在OAuth流程中始终验证参数以防止CSRF攻击
state - 使用(而非
sub)作为Google ID令牌中的唯一用户标识符email - 安全存储;它仅在首次授权时返回
refresh_token - 使用前验证外部凭证配置(确保、
token_url指向googleapis.com)service_account_impersonation_url - 对于非GCP环境,优先使用Workload Identity Federation而非服务账号密钥
- 对于GIS:使用双重提交Cookie模式验证
g_csrf_token - Python专属建议:在多次验证中复用同一个实例以实现连接池;在高频路径中不要每次调用都创建新实例
google.auth.transport.requests.Request()
Reference Files
参考文档
- OAuth 2.0 Web Server Flow — Complete OAuth 2.0 flow: parameters, consent, token exchange, refresh, revocation, incremental auth, error handling (Node.js + Python)
- ADC & Service Accounts — Application Default Credentials setup, service account keys, JWT, Compute credentials, environment configuration (Node.js + Python)
- Sign In with Google — Google Identity Services (GIS), ID token verification, CSRF protection, One Tap, FedCM (Node.js + Python)
- Workload Identity Federation — AWS, Azure, OIDC/SAML federation, workforce identity, executable-sourced credentials (Node.js + Python)
- OAuth 2.0 Web服务器流程 — 完整的OAuth 2.0流程:参数、授权同意、令牌交换、刷新、撤销、增量授权、错误处理(Node.js + Python)
- ADC & 服务账号 — Application Default Credentials配置、服务账号密钥、JWT、Compute凭证、环境配置(Node.js + Python)
- Sign In with Google — Google Identity Services(GIS)、ID令牌验证、CSRF防护、一键登录、FedCM(Node.js + Python)
- Workload Identity Federation — AWS、Azure、OIDC/SAML联邦、员工身份、可执行文件源凭证(Node.js + Python)