Generating Tokens for API Requests

Create JSON Web Tokens signed with your private key to authorize API requests.

Overview

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a way to securely transmit information. You create the token, signing it with your API Key private key.

To generate a signed JWT:

  1. Create the JWT header.
  2. Create the JWT payload.
  3. Sign the JWT.

Create JWT Header

Header Field Value
alg - Encryption Algorithm ES256. JWTs must be signed with ES256 encryption.
kid - Key Identifier Your API Key kid Ex: 97F9D4A2-6B74-4129-A755-34F2AF81F071
typ - Token Type jwt
{
  "alg": "ES256",
  "kid": "97F9D4A2-6B74-4129-A755-34F2AF81F071",
  "typ": "jwt"
}

Create JWT Payload

Header Field Value
jti - JWT id Unique token identifier to avoid request replay. Ex: random hex string: a04d7a5b89f042fa
iat - Issued At The token’s issuing time, in Unix epoch time.
exp - Expiration Time The token’s expiration time, in Unix epoch time. Cannot be more than 60 seconds after issuing time (iat)
sub - Subject (optional) Subuser UID if request must act on subuser account. See Subusers operations

Sign the JWT

Use the private key associated with the kid you specified in the header to sign the token.

See jwt.io for a list of libraries for creating and signing JWTs.

Include the JWT in the request

Include the token in the HTTP header Authorization. Do not forget to prepend the Bearer keyword to the token.

Example with curl:

curl -H 'Authorization: Bearer <JWT TOKEN>' https://exchange.savitar.io/api/v1/user

Code Samples

Generate JWT Token
const jwt = require('jsonwebtoken');
const crypto = require('crypto')

// privateKey in PEM format.
function generateJwt(kid, privateKey) {
  const now = Math.floor(Date.now() / 1000);

  const payload = {
    exp: now + 60,
    iat: now,
    jti: crypto.randomBytes(6).toString('hex'),
  }

  return jwt.sign(payload, privateKey, { algorithm: 'ES256', keyid: kid });
}
import (
  "crypto/ecdsa"
  "crypto/elliptic"
  "crypto/rand"
  "encoding/hex"
  "math/big"
  "time"

  jwt "github.com/dgrijalva/jwt-go"
)

// Uses private key as hex string.
func generateJwt(kid, key string) (string, error) {
  jti := make([]byte, 6)
  rand.Read(jti)

  now := time.Now().UTC()

  claims := jwt.StandardClaims{
    ExpiresAt: now.Add(60 * time.Second).Unix(),
    IssuedAt:  now.Unix(),
    Id:        hex.EncodeToString(jti),
  }

  i, _ := new(big.Int).SetString(key, 16)

  privKey := &ecdsa.PrivateKey{
    PublicKey: ecdsa.PublicKey{elliptic.P256(), &big.Int{}, &big.Int{}},
    D:         i,
  }

  token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
  token.Header["kid"] = kid

  return token.SignedString(privKey)
}