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

Node.js调用Coinbase Advanced Trade V3 API遇401未授权问题求助

排查Coinbase Advanced Trade V3 API 401未授权错误

使用Node.js通过axios调用Coinbase Advanced Trade最新V3 API,先尝试基于HMAC签名的认证方式,确认API密钥权限及配置无误,但调用接口时返回401/Unauthorized错误。之后改用jsonwebtoken生成Bearer令牌的认证方案,仍得到401未授权响应。以下为两种实现代码及对应错误信息,请求排查问题原因。

初始HMAC签名实现代码

const axios = require('axios');
const crypto = require('crypto');
const fs = require('fs');

const data = fs.readFileSync('/Volumes/Extreme SSD/coinbaseSecurity/coinbase_cloud_api_key.json', 'utf8');
const json = JSON.parse(data);
const apiKey  = json.name;  //'organizations/{org_id}/apiKeys/{key_id}';
const secretKey = json.privateKey;  //'-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n';

const baseURL = 'https://api.coinbase.com/api/v3/brokerage/';

function signRequest(method, path, body) {
  const timestamp = Math.floor(Date.now() / 1000).toString();

  const message = timestamp + method + path + body;

  const hmac = crypto.createHmac('sha256', secretKey);

  hmac.update(message);

  const signature = hmac.digest('hex');

  return {
    'CB-ACCESS-KEY': apiKey,
    'CB-ACCESS-SIGN': signature,
    'CB-ACCESS-TIMESTAMP': timestamp,
  };
}

async function listAccounts() {
  try {
    const method = 'GET';
    const path = 'orders/historical/batch';
    const headers = signRequest(method, path, '');
    const response = await axios.get(baseURL + path, { headers });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

初始错误响应片段

socketPath: undefined,
    method: 'GET',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/api/v3/brokerage/orders/historical/batch',
    _ended: true,
    res: IncomingMessage {
      statusCode: 401,
      statusMessage: 'Unauthorized',
      responseUrl: 'https://api.coinbase.com/api/v3/brokerage/orders/historical/batch'
}

更新后的JWT认证实现代码

const axios = require('axios');
const jwt = require('jsonwebtoken');
const fs = require('fs');

const data = fs.readFileSync('/Volumes/Extreme SSD/coinbaseSecurity/coinbase_cloud_api_key.json', 'utf8');
const json = JSON.parse(data);
const key_name = json.name; //'organizations/{org_id}/apiKeys/{key_id}'
const key_secret = json.privateKey; //'-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n'
const uuid = `/${json.principal}`

const request_method = 'GET';
const request_host = 'https://api.coinbase.com';
const request_path = '/api/v3/brokerage/accounts';
const service_name = 'retail_rest_api_proxy';

const jwt_payload = {
  aud: [service_name],
  iss: 'coinbase-cloud',
  nbf: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + 10,
  sub: key_name,
  uri: request_method + ' ' + request_host + request_path+ uuid,
};

const jwt_header = {
  kid: key_name,
  nonce: Math.floor(Date.now() / 1000).toString(),
};

const token = jwt.sign(jwt_payload, key_secret, {
  algorithm: 'ES256',
  header: jwt_header,
});

const getAccounts = async () => {
  try {
    const response = await axios.get(request_host + request_path, {
      headers: {
        Authorization: 'Bearer ' + token,
      },
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};

getAccounts();

排查要点

HMAC签名方案问题

  • 密钥类型错误:HMAC签名需要使用Coinbase生成的HMAC密钥(纯字符串),你代码中传入的是EC格式私钥,这是JWT认证专用密钥,不能用于HMAC签名。
  • 签名消息路径错误:HMAC要求消息中的路径是完整的API路径(包含/api/v3/brokerage前缀),你当前传的orders/historical/batch应该改为/api/v3/brokerage/orders/historical/batch。
  • API Key格式错误:HMAC用的CB-ACCESS-KEY是创建API时生成的ACCESS KEY(短字符串格式),不是organizations/{org_id}/apiKeys/{key_id}这种JWT用的key name。

JWT认证方案问题

  • URI字段格式错误:JWT payload中的uri只需请求方法 + 空格 + 接口路径,正确格式为GET /api/v3/brokerage/accounts,不需要拼接request_host和uuid。
  • Nonce字段不符合要求:nonce必须是唯一随机字符串,不能用时间戳,Coinbase以此防止重放攻击。
  • 私钥格式验证:确保读取的EC私钥换行符完整,没有被JSON转义破坏格式。
  • 权限确认:检查API密钥是否开启了对应接口的访问权限(如读取账户、订单权限),且密钥状态为启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:02:03