Skip to main content
Version: 6.3.3

Access APIs

This is a guide to accessing SENSA Fabric APIs.

Cortex uses SSO and RBAC for authentication and authorization. Users and roles are managed in the customer's identity provider, and administrators can grant or deny user access to Cortex Projects and resources. If you have not been granted authorization to make an API call, an error message is displayed.

info
  • The examples on this page use cURL to send HTTP requests. If you do not have cURL, download and install a cURL package for your environment.
  • This guide assumes you are accessing the Cortex API at https://api.<dci-base-domain>. Replace <dci-base-domain> with the URL set up for your Dedicated Cortex Instance.
  • Cortex CLI must be installed and you must be authenticated to the CLI to in order to access the APIs using the instructions that follow

Get Environment Variables

Use the CLI to view the env variables that you need to run curl commands more easily.

Authenticate to the CLI. Then run:

cortex configure env --profile profileName

Response:

export CORTEX_TOKEN=xxxx
export CORTEX_URI=https://api.dci-dev.dev-eks.insights.ai
export CORTEX_URL=https://api.dci-dev.dev-eks.insights.ai
export CORTEX_PROJECT=myProject

Generate a JWT in the Console

The JWT generated in the Console is a Personal Access Token (PAT) .JSON file.

  1. Login to Fabric Console and at the top right click the Settings icon(gear).

  2. Click Download to generate a PAT (Personal Access Token) .JSON file in your Downloads/ local directory.

    Example:

    {
    "jwk": {
    "crv": "Ed25519",
    "x": "5T2vvtz3SQ3VBUYOKpZtlD_aVYXsUkzQMFjxxxx",
    "d": "8iwfKo8ovl2dT5rGt3smS8eFKNh40HRHX4Zp_xxxxxx",
    "kty": "OKP",
    "kid": "zdMtZVJvPx7y1hRc2b-v4I2QdfkgtDX26_xxxxxxx"
    },
    "issuer": "cognitivescale.com",
    "audience": "cortex",
    "username": "090e1421-13b3-4550-ba5c-xxxxx",
    "url": "https://192.168.39.8iwfKo8ovl2dT5rGt3smS8eFKNh40HRHX4Zp_xxxxxx:xxxxx"
    }

Generate a JWT in the CLI

JSON Web Tokens (JWTs) are used to authorize users to interact with the Cortex APIs. JWTs are obtained from the Cortex CLI with this command:

cortex configure token

The response is a JWT for the currently active CLI user.

Store the value of the response. All Cortex API requests must include an Authorization header with the JWT value appended to the Bearer string. For example, if the value of the JWT field is ABCDEFG, then every request to Cortex should have an Authorization header with the value Bearer ABCDEFG.

Generate a signed JWT

Some Fabric integrators may not be able to use a static JWT to access services and APIs. They must obtain a signed JWT to ensure that content is not tampered with. Once the user is logged in, each subsequent request includes the JWT, allowing the user to access resources that are permitted with that token.

You must have the Python Library installed to complete the following process.

  1. From Console generate a PAT (Personal Access Token) .JSON file and save it to your local directory.
  1. If you ARE running the Cortex-Python LIB: Run the following to command to return a signed JWT:

    from cortex.utils import generate_token
    ## Get pat config using `cortex users create <user>` from cli
    PAT = {.....}
    config = PAT.get("config")
    token = generate_token(config)
    print(token)

    Returns the signed JWT.

  2. Call the API using the signed JWT as the bearer token:

    GET /cognitivescale.github.io/v4/agents/
    Authorization: Bearer SIGNED_JWT
    Host: "https://api.<dci-base-domain>/"

Make a test API request

To verify your JWT is working correctly, make a test API request using your JWT.

The example below retrieves a list of agents saved in a project. To run this command, update the following:

  • Replace {dci-base-domain} with the base-domain for your cluster.
  • Replace {projectId} with a project you have access to. To see the full list of projects, use cortex projects list.
  • Replace <JWT> with the JWT you retrieved using cortex configure token
curl -X GET https://api.{dci-base-domain}/fabric/v4/projects/{projectId}/agents \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <JWT>'

Cortex returns an agents object with a list of agents for the given project.

{
"agents":[
{
"name":"agent-1",
"environmentName":"cortex/develop",
"title":"Agent 1",
"description":"Agent description",
"tags":[

],
"createdAt":"2020-10-29T17:34:59.862Z",
"updatedAt":"2020-10-29T18:33:39.146Z"
}
]
}

If no agents are saved in the given project, Cortex returns an empty agents object.

{
"agents":[

]
}

Token expiration time

By default, the tokens generated with cortex configure token expire after 24 hours.

If you get a message that your token has expired or you get an authentication error, generate a new token using the cortex configure token command.

External API calls into Fabric

When you are making an API request into Fabric from an external resource (you are NOT using the the Cortex-Python Lib), run the following to command to return a signed JWT, created with RSA-256 using the private key.

The requests below return the signed JWT.

Python Request

def generate_token(config, validity=2):
"""
Use the Personal Access Token (JWK) obtained from the SENSA Fabric Console to generate JWTs to access Cortex services.
"""
try:
key = jwkLib.JWK.from_json(json.dumps(config.get('jwk')))
token_payload = {
"iss": config.get('issuer'),
"aud": config.get('audience'),
"sub": config.get('username'),
}
token = py_jwt.generate_jwt(token_payload, key, 'EdDSA', datetime.timedelta(minutes=validity),
other_headers={"kid": key.thumbprint()})
return token
except Exception:
noTokenmsg = 'Please Provide Your Cortex Token. For more information, go to Cortex Docs > Cortex Tools > Access'
raise BadTokenException(noTokenmsg)

:::note

The token is set to expire in 2 minutes by default (validity=2). To increase the JWT ttl specify the number of minutes. (For example validity=5 sets the signed JWT ttl to 5 minutes).

It is important to keep the signed token short lived for security. You can regenerate the token anytime because the internal SENSA Fabric token does not expire.

:::

Java request

package com.example;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.Ed25519Signer;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.json.*;

import java.io.InputStream;
import java.util.Date;

public class Main {

public static void main(String[] args) {
try {
String resourceName = "/cortex-token.json";
InputStream is = Main.class.getResourceAsStream(resourceName);
if (is == null) {
throw new NullPointerException("Cannot find resource file " + resourceName);
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
String issuer = object.getString("issuer");
String audience = object.getString("audience");
String url = object.getString("url");
String username = object.getString("username");
JSONObject jwk = object.getJSONObject("jwk");
JWK cortexJwk = JWK.parse(jwk.toMap());

// Create the EdDSA signer
JWSSigner signer = new Ed25519Signer(cortexJwk.toOctetKeyPair());

// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(username)
.issuer(issuer)
.audience(audience)
.expirationTime(new Date(new Date().getTime() + 60 * 1000))
.build();

SignedJWT signedJWT = new SignedJWT(
new JWSHeader.Builder(JWSAlgorithm.EdDSA).keyID(cortexJwk.getKeyID()).build(),
claimsSet);

// Compute the EC signature
signedJWT.sign(signer);

// Serialize the JWS to compact form
String s = signedJWT.serialize();
System.out.println(s);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

note

The token is set to expire in 1 minute in the example above (.expirationTime(new Date(new Date().getTime() + 60 * 1000))). To specify the JWT ttl set number of seconds x 1000. (For example 180 * 1000 sets the ttl to 180 milliseconds or 3 minutes).

It is important to keep the signed token short lived for security. You can regenerate the token anytime because the internal SENSA Fabric token does not expire.