Authentication


Authentication


All requests to the Powered by CData API must be properly authenticated using JSON Web Tokens (JWT).

CData requires that a JWT is signed using the RSA 256 algorithm.

Creating a JWT

Follow these steps to create a JWT.

  1. Create a JWT header with this format:

    {"alg:"RS256", typ:"JWT"}

  2. Base64url encode the JWT header.

  3. Construct a JSON Claims Set for the JWT with the following parameters.

    Parameter Description
    tokenType powered-by (This JWT token is type powered-by.)
    iat The time the JWT is issued, expressed as the number of seconds from 1970-01-01T0:0:0Z measured in UTC.
    exp The date and time at which the token expires, expressed as the number of seconds from 1970-01-01T0:0:0Z measured in UTC.
    iss The account Id of the parent account.
    sub The account Id of the child account (optional for Create Account and List Data Sources).

    The following is an example JSON Claim Set for the JWT:

     {
       "tokenType": "powered-by",
       "iat": current_time_seconds,
       "exp": expiration_time_seconds,
       "iss": "fbb6efcd-fa7a-4eca-b9ad-1f1770edb012",
       "sub": "b21c47ad-9551-4cc1-b9b3-b9db6d426271",
     }
    
  4. Base64url encode the JSON Claims Set without any line breaks.

  5. Create a string for the encoded JWT Header and the encoded JWT Claims Set in the following format:

    Base64UrlEncode(JWT_header)` + "." + Base64UrlEncode(JWT_Claims_Set)
    
  6. Sign the token with your private key and format the token.

  7. Register the public key certificate in Privacy-Enhanced Mail (PEM) format in the management account. Open a support ticket with CData Connect Cloud to register the public key.

Generating JWT Keys

A JWT requires a public and private key in PEM format. You sign the JWT with your private key and you register the public key with CData. There are several ways to generate JWT keys. The examples below use openssl.

Generating a Private Key

The following example shows how to generate the JWT private key using openssl:

openssl genrsa -out ./private.key 4096

Your current directory should now contain the private.key. Do not share this file with anyone!

Generating a Public Key

Use the private key to generate the public key. In openssl, the command is as follows:

openssl rsa -in private.key -pubout -outform PEM -out public.key

Your current directory should now contain the public.key, which you need to share with CData.

Code Samples

Code samples for creating a JWT are available in the following programming languages:

Java

Creating a JWT in Java:

import org.apache.commons.codec.binary.Base64;
import java.io.*; 
import java.security.*; 
import java.text.MessageFormat;  

public class JWTExample {

  public static void main(String[] args) {

    String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}";
    String claimTemplate = "'{
    '\"typ\": \"{0}\", 
      \"iat\": \"{1}\", 
      \"exp\": \"{2}\", 
      \"iss\": \"{3}\", 
      \"sub\": \"{4}\"'
      }'";

    try {
      StringBuffer token = new StringBuffer();

      //Encode the JWT Header and add it to our string to sign
      token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

      //Separate with a period
      token.append(".");

      //Create the JWT Claims Object
      String[] claimArray = new String[5];
      claimArray[0] = "powered-by";
      claimArray[1] = Long.toString( System.currentTimeMillis()/1000 );
      claimArray[2] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
      claimArray[3] = "fbb6efcd-fa7a-4eca-b9ad-1f1770edb012";
      claimArray[4] = "b21c47ad-9551-4cc1-b9b3-b9db6d426271";
      claims = new MessageFormat(claimTemplate);
      String payload = claims.format(claimArray);

      //Add the encoded claims object
      token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

      //Load the private key from a keystore
      KeyStore keystore = KeyStore.getInstance("JKS");
      keystore.load(new FileInputStream("./path/to/keystore.jks"), "keystorepassword".toCharArray());
      PrivateKey privateKey = (PrivateKey) keystore.getKey("certalias", "privatekeypassword".toCharArray());

      //Sign the JWT Header + "." + JWT Claims Object
      Signature signature = Signature.getInstance("SHA256withRSA");
      signature.initSign(privateKey);
      signature.update(token.toString().getBytes("UTF-8"));
      String signedPayload = Base64.encodeBase64URLSafeString(signature.sign());

      //Separate with a period
      token.append(".");

      //Add the encoded signature
      token.append(signedPayload);

      System.out.println(token.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

Python

Creating a JWT in Python:

Use the PyJWT library in Python. You can install it via pip: pip install pyjwt.

import jwt
import datetime

# Secret key used to sign the JWT
secret_key = 'your_secret_key_here'

# Payload (claims) for the JWT

current_datetime_seconds = datetime.now()/1000
expiration_datetime_seconds = current_datetime_seconds + timedelta(minutes=5) 

payload = 
  {
    'tokenType': 'powered-by',
    'iat': current_datetime_seconds,
    'exp': expiration_datetime_seconds,
    'iss': 'fbb6efcd-fa7a-4eca-b9ad-1f1770edb012',
    'sub': 'b21c47ad-9551-4cc1-b9b3-b9db6d426271',
  }

# Create the JWT token
token = jwt.encode(payload, secret_key, algorithm='HS256')

print(encoded)

C#

Creating a JWT in C#:

Use the Nuget Package Manager Console to install the System.IdentityModel.Tokens.Jwt library with the following command:

Install-Package System.IdentityModel.Tokens.Jwt

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;


// Secret key used to sign the JWT
var secretKey = "your_secret_key_here";

// Create an rsa security key from the secret key
var rsa = new RSACryptoServiceProvider();
rsa.ImportRSAPrivateKey(Convert.FromBase64String(secretKey), out _);

// Create signing credentials using the security key
SigningCredentials signingCredentials = new(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256);

DateTime currentTime = DateTime.UtcNow;
DateTime expirationTime = currentTime.AddMinutes(5);

// Create claims for the JWT payload
var claims = new[]
{
   new Claim(JwtRegisteredClaimNames.Iss, "your_oem_account_id_here"),
   new Claim(JwtRegisteredClaimNames.Sub, "your_sub_account_id_here"),
   new Claim("JwtRegisteredClaimNames.Typ", "powered-by"),
};

// Create a JWT token descriptor with claims and signing credentials
var tokenDescriptor = new SecurityTokenDescriptor
{
   Subject = new ClaimsIdentity(claims),
   SigningCredentials = signingCredentials,
   Expires = expirationTime,
   IssuedAt = currentTime
};

// Create a JWT token handler
var tokenHandler = new JwtSecurityTokenHandler();

// Create and encode the JWT token
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

Console.WriteLine(tokenString);
Console.ReadLine();

node.js

Creating a JWT in node.js:

const jwt = require('jsonwebtoken');

// Claims
const currentTimeInSeconds = Math.floor(Date.now() / 1000); // Convert milliseconds to seconds
const expirationTimeInSeconds = currentTimeInSeconds + (60 * 5); // Example: 5 min

const claims = 
{
  tokenType: 'powered-by',
  iat: currentTimeInSeconds,
  exp: expirationTimeInSeconds,
  iss: 'fbb6efcd-fa7a-4eca-b9ad-1f1770edb012',
  sub: 'b21c47ad-9551-4cc1-b9b3-b9db6d426271',
};

// Secret key to sign the token
const secretKey = 'your_secret_key_here';

// Generate JWT token
const token = jwt.sign(claims, secretKey);

console.log(token);

To run the code, save index.js and execute it as follows:

node index.js