A JSON Web Token (JWT) is a a secure method of authenticating API calls used by Coinbase Developer Platform. They combine encryption and access management in a single token, offering a robust security layer compared to traditional API keys.

Generating a JWT

Regardless of which code snippet you use, follow these steps:

  1. Replace key name and key secret with your key name and private key. key secret is a multi-line key and newlines must be preserved to properly parse the key. Do this on one line with \n escaped newlines, or with a multi-line string.
  2. Update the request_path and request_host or url variables as needed depending on which endpoint is being targeted.
  3. Run the generation script that prints the command export JWT=....
  4. Run the generated command to save your JWT.

Your JWT expires after 2 minutes, after which all requests are unauthenticated.

Code samples for ECDSA Keys

The easiest way to generate a JWT is to use the built-in functions in our SDKs. See the relevant product docs like Advanced Trade SDK, or CDP SDK, for examples.

These code samples are for ECDSA Signature algorithm keys. Ed25519 code samples below.

  1. Install dependencies PyJWT and cryptography.
pip install PyJWT==2.8.0
pip install cryptography==42.0.5
  1. Update the request_path and request_host variables as needed depending on which endpoint is being targeted.
  2. In the console, run: python main.py (or whatever your file name is).
  3. Set the JWT to that output, or export the JWT to the environment with export JWT=$(python main.py).
  4. Make your request, example curl -H "Authorization: Bearer $JWT" 'https://api.coinbase.com/api/v3/brokerage/accounts'
import jwt
from cryptography.hazmat.primitives import serialization
import time
import secrets

key_name       = "organizations/{org_id}/apiKeys/{key_id}"
key_secret     = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"
request_method = "GET"
request_host   = "api.coinbase.com"
request_path   = "/api/v3/brokerage/accounts"
def build_jwt(uri):
    private_key_bytes = key_secret.encode('utf-8')
    private_key = serialization.load_pem_private_key(private_key_bytes, password=None)
    jwt_payload = {
        'sub': key_name,
        'iss': "cdp",
        'nbf': int(time.time()),
        'exp': int(time.time()) + 120,
        'uri': uri,
    }
    jwt_token = jwt.encode(
        jwt_payload,
        private_key,
        algorithm='ES256',
        headers={'kid': key_name, 'nonce': secrets.token_hex()},
    )
    return jwt_token
def main():
    uri = f"{request_method} {request_host}{request_path}"
    jwt_token = build_jwt(uri)
    print(jwt_token)
if __name__ == "__main__":
    main()

Code samples for Ed25519 Keys

These code samples are for Ed25519 Signature algorithm keys.

  1. Install the libsodium-wrappers and base64url libraries.
npm i libsodium-wrappers base64url
  1. Update the request_path and url variables as needed depending on which endpoint is being targeted.
  2. In the console, run: node main.js (or whatever your file name is).
  3. Set JWT to that output, or export the JWT to environment with export JWT=$(node main.js).
  4. Make your request, example curl -H "Authorization: Bearer $JWT" 'https://api.coinbase.com/api/v3/brokerage/accounts'
const _sodium = require('libsodium-wrappers');
const base64url = require("base64url");
const crypto = require('crypto');

const key_name = "KEY_ID";
const key_secret = "PRIVATE_KEY";
const request_method = 'GET';
const url = 'api.coinbase.com';
const request_path = '/api/v3/brokerage/products';
const uri = request_method + ' ' + url + request_path;

const getJWT = async () => {  
    await _sodium.ready;
    const sodium = _sodium;
    const privateKey = key_secret;
    const payload = {
        iss: 'cdp',
        nbf: Math.floor(Date.now() / 1000),
        exp: Math.floor(Date.now() / 1000) + 120,
        sub: key_name,
        uri,
     };  
     const {headerAndPayloadBase64URL, keyBuf} = encode(payload, privateKey, "EdDSA");
     const signature = sodium.crypto_sign_detached(headerAndPayloadBase64URL, keyBuf); 
     const signatureBase64url = base64url(Buffer.from(signature));
     console.log(`${headerAndPayloadBase64URL}.${signatureBase64url}`)
};

const encode = (payload, key, alg) => {
    const header = {
        typ: "JWT",
        alg,
        kid: key_name,
        nonce: crypto.randomBytes(16).toString('hex'),
    };
    const headerBase64URL = base64url(JSON.stringify(header));
    const payloadBase64URL = base64url(JSON.stringify(payload));
    const headerAndPayloadBase64URL = `${headerBase64URL}.${payloadBase64URL}`;
    const keyBuf = Buffer.from(key, "base64");
    return {headerAndPayloadBase64URL, keyBuf};
};

getJWT();

Using a JWT

Use your generated JWT by including it as a bearer token within your request:

Note that your JWT is only valid for a period of 2 minutes from the time it is generated. You’ll need to re-generate your JWT before it expires to ensure uninterrupted access to our APIs.

Shell
curl -L -X <HTTP_METHOD> "<API_ENDPOINT_URL>" \
  -H "Authorization: Bearer $JWT" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json"

Here’s a sample request to the Get Asset by ID endpoint, using a redacted JWT:

Shell
curl -L -X POST "https://api.cdp.coinbase.com/platform/v1/networks/base-mainnet/assets/BTC" \
  -H "Authorization: Bearer eyJ...IYg" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json"

Learn More about JWTs

JWTs are a secure method of authenticating API calls, especially crucial for platforms handling sensitive financial information. They combine encryption and access management in a single token, offering a robust security layer compared to traditional API keys.

At Coinbase, upholding our motto “The most trusted name in Crypto” means ensuring the utmost security in every aspect of our operations. As digital threats evolve, so must our methods of safeguarding user data. This is why we employ JSON Web Tokens (JWTs) for API authentication—a format that not only verifies identity but also encrypts critical information within a secure token framework.

What is a JSON Web Token (JWT)?

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. At Coinbase, JWTs encapsulate the claims in a JSON object that can be digitally signed or encrypted. Each JWT consists of three parts: the Header, the Payload, and the Signature. We’ll dive deeper into each of these below.

The Anatomy of a JWT

Understanding the structure of a JSON Web Token (JWT) is key to leveraging its full potential for secure API interactions. A JWT consists of three distinct parts:

  • Header: This section declares the type of the token, JWT, and the algorithm used for the signature, such as ES256 in Coinbase’s case, which are critical for ensuring the security and integrity of the token.
  • Payload: Containing claims such as the user’s identity, role, and token expiration time. At Coinbase, this data is crucial for enabling not just authentication but also for ensuring that each transaction aligns with our user’s privileges and security requirements.
  • Signature: The final component is a cryptographic signature that verifies that the token comes from a trusted source and has not been altered. This ensures that the transaction is both secure and verifiable. This structure not only ensures compliance with rigorous security standards but also supports transparent and trustworthy transactions across our platform.

Why Use JWTs for API Authentication?

In the realm of financial transactions, where security cannot be compromised, JWTs offer a sophisticated method for authenticating API calls that goes beyond traditional approaches. At Coinbase, our commitment to being “The most trusted name in Crypto” necessitates a framework that not only enhances security but also efficiently handles the scale and complexity of modern financial systems.

JWTs excel in this environment due to several key features:

  • Improved Security Features: JWTs provide a robust mechanism for ensuring data integrity and authenticity. By using advanced algorithms for signatures, each token is secured against tampering, crucial for protecting sensitive financial data.
  • Stateless Nature: Unlike session-based authentication, JWTs do not require server-side storage to verify each request. This statelessness enables our systems to scale dynamically without the overhead of session management, critical in handling high volumes of transactions seamlessly.
  • Detailed Control Over User Permissions and Token Expiration: JWTs contain detailed claims that specify user roles and access privileges, allowing for fine-grained access control. Furthermore, token expiration is explicitly managed within the JWT, ensuring that permissions are timely and securely revoked when necessary.

These features make JWTs an integral part of our security strategy, ensuring that every API interaction remains secure, scalable, and aligned with our stringent security standards.

When dealing with APIs across different environments or with multiple endpoints, it’s wise to extract and verify each component of the URI:

  1. HTTP Method: Ensure it matches the requirements (e.g., GET, POST).
  2. Host: Check if it corresponds to the correct API server (e.g., api.coinbase.com, api.developer.coinbase.com).
  3. Endpoint Path: Verify the path that corresponds to the specific API functionality you need (e.g., /api/v3/brokerage/accounts).

Common Pitfalls and How to Avoid Them

  • Dynamic Parameters: Passing the HTTP method, and the correctly formatted URL domain and URL path. This would require the variables assigned to these parameters to be dynamic in nature and to be set, at runtime to the API endpoint being queried.
  • Token Expiration: manage the token expiration to a timeframe which makes sense for your use-case (ie. adding more time for latency if using a proxy.) For reference, our samples all set the expiration to 120 seconds, or 2 minutes.
  • Format and Import API Keys: keep original key formatting and import both the name and private key appropriately into the JWT creation file. If running into authentication issues after following all the above steps, consider adding debugging to see what the actual private key and key name resolve to at runtime.
  • Clock Skew Issues: JWTs depend on synchronized timestamps for nbf (Not Before) and exp (Expiration) claims. Even small discrepancies between server and client clocks can cause tokens to be rejected. Ensure systems are synchronized using a reliable time source, such as NTP.
  • Improper Header Configuration: Ensure the JWT header includes the correct alg (Algorithm) and kid (Key ID). Misconfigurations can result in failed verifications. Follow Coinbase guidelines to set these fields accurately.
  • Payload Bloat: Avoid adding unnecessary data to the JWT payload. Overloading the payload can increase token size, leading to performance issues and potential exposure of sensitive information. Include only essential claims needed for the specific API request.