I don’t get my nodejs code working for the REST API when a JWT is needed. The web socket (different code) using the same keys is working fine, a REST call to “time” (public service) is also working fine. Why is the JWT failing?
AxiosError: Request failed with status code 401
This is my code:
const { sign } = require('jsonwebtoken');
const crypto = require('crypto');
const axios = require('axios');
// Configuration for JWT
const key_name = 'organizations/...';
const key_secret = '-----BEGIN EC PRIVATE KEY-----\n...-----END EC PRIVATE KEY-----\n';
// What and Where:
const url = 'https://api.coinbase.com';
const service_name = "retail_rest_api_proxy"
const request_method = 'GET';
const request_path = '/api/v3/brokerage/accounts'; // time works fine, accounts does not
const algorithm = 'ES256';
const uri = request_method + ' ' + url + request_path;
const token = sign(
{
aud: [service_name],
iss: 'coinbase-cloud',
nbf: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 120,
sub: key_name,
uri,
},
key_secret,
{
algorithm,
header: {
kid: key_name,
nonce: crypto.randomBytes(16).toString('hex'),
},
}
);
// Configuring the API request
let config = {
method: request_method,
url: url + request_path,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}` // Adding the Authorization header
}
};
// Executing the API call with axios
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
Thanks!