google-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google Authentication for Node.js & Python

Node.js 和 Python 中的 Google 认证

Libraries

相关库

Node.js

Node.js

  • google-auth-library
    — core auth library (OAuth2Client, GoogleAuth, JWT, Compute, Impersonated)
  • googleapis
    — Google API client (wraps google-auth-library)
bash
npm install google-auth-library
npm install googleapis
  • google-auth-library
    — 核心认证库(包含OAuth2Client、GoogleAuth、JWT、Compute、Impersonated)
  • googleapis
    — Google API客户端(封装了google-auth-library)
bash
npm install google-auth-library
npm install googleapis

Python

Python

  • google-auth
    — core auth library (google.oauth2, google.auth, credentials, transport)
  • google-auth-oauthlib
    — OAuth 2.0 user-credential flow helpers (Flow, InstalledAppFlow)
  • google-api-python-client
    — Google API client (wraps google-auth)
bash
pip install google-auth
pip install google-auth-oauthlib
pip install google-api-python-client
  • google-auth
    — 核心认证库(包含google.oauth2、google.auth、credentials、transport)
  • google-auth-oauthlib
    — OAuth 2.0用户凭证流程工具(包含Flow、InstalledAppFlow)
  • google-api-python-client
    — Google API客户端(封装了google-auth)
bash
pip install google-auth
pip install google-auth-oauthlib
pip install google-api-python-client

Authentication Methods Overview

认证方法概览

MethodUse CaseNode.js Key ClassPython Key Module / Class
ADCSame identity for all users, server-to-server
GoogleAuth
google.auth.default()
OAuth 2.0Actions on behalf of end users
OAuth2Client
google_auth_oauthlib.flow.Flow
Sign In with Google (GIS)User sign-in/sign-up on websitesGIS JS SDK +
verifyIdToken()
GIS JS SDK +
id_token.verify_oauth2_token()
JWT / Service AccountServer-to-server, single identity
JWT
service_account.Credentials
API KeyPublic data, no user context
OAuth2Client({ apiKey })
passed to
googleapiclient.discovery.build(developerKey=)
ComputeOn GCP with attached service account
Compute
google.auth.compute_engine.Credentials
Workload Identity FederationAWS/Azure/OIDC → GCP without SA keys
ExternalAccountClient
google.auth.identity_pool.Credentials
/
google.auth.aws.Credentials
认证方法适用场景Node.js核心类Python核心模块/类
ADC所有用户使用同一身份,服务器到服务器通信
GoogleAuth
google.auth.default()
OAuth 2.0代表终端用户执行操作
OAuth2Client
google_auth_oauthlib.flow.Flow
Sign In with Google (GIS)网站用户登录/注册GIS JS SDK +
verifyIdToken()
GIS JS SDK +
id_token.verify_oauth2_token()
JWT / 服务账号服务器到服务器通信,单一身份
JWT
service_account.Credentials
API密钥公开数据访问,无用户上下文
OAuth2Client({ apiKey })
传入
googleapiclient.discovery.build(developerKey=)
Compute在GCP上使用附加服务账号
Compute
google.auth.compute_engine.Credentials
Workload Identity FederationAWS/Azure/OIDC → GCP,无需服务账号密钥
ExternalAccountClient
google.auth.identity_pool.Credentials
/
google.auth.aws.Credentials

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 →
gcloud auth application-default login
file →
GOOGLE_APPLICATION_CREDENTIALS
env var.
For 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 login
生成的文件 →
GOOGLE_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,
aud
,
exp
,
iss
(accounts.google.com).
For 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签名、
aud
exp
iss
(accounts.google.com)。
如需了解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'] )
undefined
credentials = service_account.Credentials.from_service_account_info( info, scopes=['https://www.googleapis.com/auth/cloud-platform'] )
undefined

5. 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 datetime
Node.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
    client_secret
    or service account keys in client-side code
  • Always validate
    state
    parameter to prevent CSRF in OAuth flows
  • Use
    sub
    (not
    email
    ) as the unique user identifier from Google ID tokens
  • Store
    refresh_token
    securely; it's only returned on first authorization
  • Validate external credential configurations before use (check
    token_url
    ,
    service_account_impersonation_url
    point to googleapis.com)
  • Prefer Workload Identity Federation over service account keys for non-GCP environments
  • For GIS: verify
    g_csrf_token
    with double-submit-cookie pattern
  • Python-specific: reuse a single
    google.auth.transport.requests.Request()
    instance across verifications for connection pooling; do not create a new one per call in hot paths
  • 切勿在客户端代码中暴露
    client_secret
    或服务账号密钥
  • 在OAuth流程中始终验证
    state
    参数以防止CSRF攻击
  • 使用
    sub
    (而非
    email
    )作为Google ID令牌中的唯一用户标识符
  • 安全存储
    refresh_token
    ;它仅在首次授权时返回
  • 使用前验证外部凭证配置(确保
    token_url
    service_account_impersonation_url
    指向googleapis.com)
  • 对于非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)