You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript使用服务账号获取无需用户授权的Google APIs访问令牌

用JavaScript通过服务账号获取无用户授权的Google API访问令牌

服务账号的方式仅适用于Node.js服务器端环境,绝对不能在浏览器端使用——因为服务账号的密钥文件一旦暴露,会导致你的Google Cloud资源面临安全风险。具体步骤如下:

  1. 安装官方认证库:
npm install google-auth-library
  1. 编写代码获取令牌:
const { GoogleAuth } = require('google-auth-library');

async function fetchServiceAccountToken() {
  // 加载本地的服务账号密钥JSON文件(从Google Cloud控制台下载)
  const auth = new GoogleAuth({
    keyFile: './your-service-account-key.json',
    // 替换为你需要访问的API权限范围,比如Drive只读、Cloud Storage读写等
    scopes: ['https://www.googleapis.com/auth/drive.readonly'],
  });

  const authClient = await auth.getClient();
  const tokenResult = await authClient.getAccessToken();
  const accessToken = tokenResult.token;
  
  console.log('获取到的访问令牌:', accessToken);
  return accessToken;
}

// 调用函数
fetchServiceAccountToken().catch(err => console.error('获取令牌失败:', err));
其他无需用户授权的令牌获取方式

除了服务账号,还有两种符合需求的方式,分别对应不同的凭证类型:

1. 直接使用API Key

API Key仅适用于公开可访问的Google API端点(比如Google Maps静态地图、YouTube Data API的公开视频查询),不需要获取令牌,直接在请求的URL参数中加入key=YOUR_API_KEY即可。

注意:API Key权限有限,无法访问需要私有权限的资源(比如用户的个人Drive文件、私有Cloud Storage桶),且只能用于无需身份验证的公开操作。

2. 客户端凭证流(Client Id + Client Secret)

这种方式适用于服务器端应用,用来访问属于应用自身的资源(而非用户个人资源),流程是直接向Google OAuth2服务器请求令牌:

const axios = require('axios');

async function fetchClientCredentialsToken() {
  try {
    const response = await axios.post('https://oauth2.googleapis.com/token', null, {
      params: {
        grant_type: 'client_credentials',
        client_id: 'YOUR_CLIENT_ID', // 从Google Cloud控制台获取
        client_secret: 'YOUR_CLIENT_SECRET', // 从Google Cloud控制台获取
        scope: 'https://www.googleapis.com/auth/cloud-platform' // 替换为目标API范围
      }
    });

    console.log('访问令牌:', response.data.access_token);
    return response.data.access_token;
  } catch (err) {
    console.error('请求失败:', err.response.data);
  }
}

fetchClientCredentialsToken();

注意:Client Secret绝对不能暴露在浏览器或客户端代码中,只能在服务器端安全环境下使用。这种方式同样无法访问用户的私有数据,仅能操作应用自身拥有权限的资源。

内容的提问来源于stack exchange,提问作者Aftab Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:10:30