@cef-ebsi/app-jwt
TypeScript icon, indicating that this package has built-in type declarations

0.0.13 • Public • Published

EBSI Logo

EBSI App JWT Library

Library to create sessions between Apps registered in the Trusted App Registry.

Table of Contents

  1. Installation
  2. Usage
  3. Library Test
  4. Licensing

Installation

npm install @cef-ebsi/app-jwt

or if you use yarn

yarn add @cef-ebsi/app-jwt

Usage

Sessions

In the following example the app "ebsi-wallet" (Agent) creates a request to access "ebsi-ledger" (Relying Party).

const { Agent, Scope } = require("@cef-ebsi/app-jwt");

// The client "ebsi-wallet" creates a request to access the "ebsi-ledger"
const cliPrivKey =
  "64e4a7a1e2e463e95e2e3413deb7676221544e92b951705142fd9c719ea4af3e";
const agent = new Agent(Scope.COMPONENT, cliPrivKey, { issuer: "ebsi-wallet" });
const request = await agent.createRequestPayload("ebsi-ledger");
console.log(request);
/*
{
  grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
  assertion: 
   'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksiLCJraWQiOiJHNW01TmxiaTdGWlhPTVlHN2ctZ0tCLVVGdkVBSVUyUFkzSFQ3SFZtYkJzIn0.eyJpc3MiOiJlYnNpLXdhbGxldCIsImF1ZCI6ImVic2ktbGVkZ2VyIiwiaWF0IjoxNTkxODkxMDU4LCJleHAiOjE1OTE4OTEwNzN9.rvuAbEAOof5hilA3vdcWg_d81MAGSSMWGlR-kJ15ZqzlZQgbzGCAJHlG1jK3UGh2NP_cFRivfSErT-K_7HrV4g',
  scope: 'ebsi profile component'
}
*/

The Agent makes a call to "ebsi-ledger" (Relying Party) in the endpoint "/sessions" and put this request in the body as Content-Type: application/json.

The Relying Party receives this request and creates a new session using the class "Session":

const { Session } = require("@cef-ebsi/app-jwt");
const express = require("express");
const router = express.Router();

const apiPrivKey =
  "9d678b6edef394cd0182cbc76be7fd69021c2d90c8739837737afea3723314e2";
const apiName = "ebsi-ledger";
const tarProvider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const didResolver = "https://api.intebsi.xyz/did/v1/identifiers";
const session = new Session(apiName, apiPrivKey, tarProvider, didResolver);

router.post("/sessions", async (req, res, next) => {
  try {
    const response = await session.newSession(req.body);
    res.send(response);
  } catch (error) {
    next(error);
  }
});

module.exports = router;

The response is a json object containing accessToken, tokenType, expiresIn, and issuedAt:

{ accessToken:
   'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksiLCJraWQiOiI3ZHptUzdma3ZKbWQtZjVOMGlwdjhiZXU4QWJiUTFoYnJjVG5yQS1TOERRIn0.eyJpc3MiOiJlYnNpLWxlZGdlciIsImF1ZCI6ImVic2ktbGVkZ2VyIiwiaWF0IjoxNTkxODkyMDI5LCJleHAiOjE1OTE4OTI5Mjl9.XTaX7MNi0ZsCAdtNHf4ZcGFc3zwz4roXjE2zymC6wIZIOy10Css5Pd-J2QY1RxU8NTrWxo8bnQqWvuXG1GdLIg',
  tokenType: 'Bearer',
  expiresIn: 900,
  issuedAt: 1591892029205
}

The Agent uses the accessToken to consume the api services.

Finally, the Relying Party verifies the signature and audience of this token to give access to the services:

const { Session } = require("@cef-ebsi/app-jwt");
const express = require("express");
const router = express.Router();

const apiPrivKey =
  "9d678b6edef394cd0182cbc76be7fd69021c2d90c8739837737afea3723314e2";
const apiName = "ebsi-ledger";
const tarProvider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const didResolver = "https://api.intebsi.xyz/did/v1/identifiers";
const session = new Session(apiName, apiPrivKey, tarProvider, didResolver);

function getToken(req) {
  const token = req.get("authorization");
  if (token) return token.replace("Bearer ", "");
  return null;
}

const handleToken = async (req, res, next) {
  const token = getToken(req);

  try {
    session.verify(token);
  } catch (error) {
    next(error);
    return;
  }

  req.authenticated = true;
  next();
};

router.get("/files", handleToken, async (req, res, next) => {
  /*
   * access services
   */
});

module.exports = router;

Reference: https://ec.europa.eu/cefdigital/wiki/display/BLOCKCHAININT/RFC+DID+Auth+in+EBSI+V1

Sessions supporting user scope

When a JWT is signed by a compononent or entity it can be verified using the Trusted App Registry. However, in the case of users it is validated using the DID document, then for this case the Session class also needs a did resolver.

First the user creates a request using the Agent class:

const { Agent, Scope } = require("@cef-ebsi/app-jwt");
const privKeyUser =
  "64e4a7a1e2e463e95e2e3413deb7676221544e92b951705142fd9c719ea4af3e";
const agent = new Agent(Scope.USER, privKeyUser);
const opts = { ticket: "my ticket" };
const request = await agent.createRequestPayload("api", opts);
console.log(request);

/*
{
  grantType: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
  assertion: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NkstUiJ9.eyJpYXQiOjE1OTI0MDE2NTgsImV4cCI6MTU5MjQwMTY3MywiaXNzIjoiZGlkOmVic2k6MHgzMDdhNTVCMjA5NzExNEVDREJjMmQwZTM3OWFmM2RDMzM1YjAzNGE3IiwiYXVkIjoiYXBpIiwicHVibGljS2V5IjoiMHhlY2U5MjRlNDc2NmIxZWNmODg0ZDMyNTViNjlmZjhmY2U0NmM4NWU3ZjBlOTA2OGNjNTkxMzg2NWRjMzlmMDQyNzNlNWUyZjQyZDBjNDRhNjZlNTNmMDY0NWZkZDZlN2RjYTM3NmQ3NGExMDFhZjJiOWZhYTg1NWIzZGM0ZjkwZCIsImRpZCI6ImRpZDplYnNpOjB4MzA3YTU1QjIwOTcxMTRFQ0RCYzJkMGUzNzlhZjNkQzMzNWIwMzRhNyIsInRpY2tldCI6Im15IHRpY2tldCJ9.DBjIpV2PhDGXcHYyR8PSSKBaLmy-59EXbyGuJqmqhnx_s4OrZyzkbL6_kWyIXEhVtCT61f6s2S6s7tpoPdn7cgE',
  scope: 'ebsi profile user'
}
*/

The assertion in this request automatically includes the did and publicKey in the token payload:

{
  "iat": 1592401658,
  "exp": 1592401673,
  "iss": "did:ebsi:0x307a55B2097114ECDBc2d0e379af3dC335b034a7",
  "aud": "api",
  "publicKey": "0xece924e4766b1ecf884d3255b69ff8fce46c85e7f0e9068cc5913865dc39f04273e5e2f42d0c44a66e53f0645fdd6e7dca376d74a101af2b9faa855b3dc4f90d",
  "did": "did:ebsi:0x307a55B2097114ECDBc2d0e379af3dC335b034a7",
  "ticket": "my ticket"
}

The Agent makes a call to the "api" (Relying Party) in the endpoint "/sessions" and put this request in the body as Content-Type: application/json.

The Relying Party receives this request and creates a new session. In this case the Session class is constructed using a resolver for DIDs:

const { Session } = require("@cef-ebsi/app-jwt");
const express = require("express");
const router = express.Router();

const tarProvider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const didResolver = "https://api.intebsi.xyz/did/v1/identifiers";
const session = new Session(apiName, apiPrivKey, tarProvider, didResolver);

router.post("/sessions", async (req, res, next) => {
  try {
    const response = await session.newSession(req.body);
    res.send(response);
  } catch (error) {
    next(error);
  }
});

module.exports = router;

The response is a json object containing accessToken, tokenType, expiresIn, and issuedAt. Then the user uses the accessToken to access the api services.

Options

Define a custom resolver for DIDs:

const { Resolver } = require("did-resolver");
const { getResolver } = require("ebsi-did-resolver");
const { Session } = require("@cef-ebsi/app-jwt");
const express = require("express");
const router = express.Router();

const tarProvider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const ebsiDidResolver = getResolver({
  rpcUrl: "https://api.intebsi.xyz/ledger/v1/blockchains/besu",
  registry: "0xe7dEe457E211825F66a07fAC5e4f237f8a845FE1",
});
const didResolver = new Resolver(ebsiDidResolver);
const session = new Session(apiName, apiPrivKey, tarProvider, didResolver);

Set a different expiration time for the request token and access token (by default 15 and 900 respectively):

const expiration = {
  requestToken: 20,
  accessToken: 800,
};
const agent = new Agent(Scope.COMPONENT, cliPrivKey, {
  issuer: "ebsi-wallet",
  expiration,
});
const session = new Session(
  apiName,
  apiPrivKey,
  tarProvider,
  didResolver,
  expiration
);

Contruct Session using different formats of private key (ECKey, PEM, HEX supported):

const key = jose.JWK.generateSync("EC", "secp256k1");
const keyPEM = key.toPEM(true);
const keyHEX = Buffer.from(key.d as string, "base64").toString("hex");

const session1 = new Session(apiName, key);
const session2 = new Session(apiName, keyPEM);
const session3 = new Session(apiName, keyHEX);

Define more fields in the payload of the request:

const { Agent, Scope } = require("@cef-ebsi/app-jwt");

const agentUser = new Agent(Scope.USER);
const requestUser = await agentUser.createRequestPayload("api", {
  ticket: "my ticket",
  name: "eva",
});

const agentEntity = new Agent(Scope.ENTITY);
const requestEntity = await agentEntity.createRequestPayload("api", {
  nonce: "123",
});

const agentComponent = new Agent(Scope.COMPONENT);
const requestComponent = await agentComponent.createRequestPayload("api", {
  sub: "my app",
});

Create sessions with adding more fields to the token payload:

const { Session, Agent, Scope } = require("@cef-ebsi/app-jwt");
const session = new Session("api");
const agent = new Agent(Scope.USER);
const opts = { ticket: "my ticket" };
const requestUser = await agent.createRequestPayload("api", opts);

const extraPayload = { userName: "eva", aud: "overwriting aud" };
const result = await session.newSession(requestUser, extraPayload);

Trusted App Registry

Get the public key of a Trusted App in PEM format:

const { TrustedAppRegistry } = require("@cef-ebsi/app-jwt");
const provider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const tar = new TrustedAppRegistry(provider);
const pubKey = await tar.getPublicKey("ebsi-wallet");
console.log(pubKey);
/*
-----BEGIN PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAErIVa2go50gSs5pCDF5wY+fb5+TzTzyCW
A9R8Ljuu5Xzz3ILh3U/
NtkCsKr5gjXuHMVXdkM4yWP0by59EoGXyjw==
-----END PUBLIC KEY-----
*/

Check if a token has been issued by a Trusted App and verify it:

const { TrustedAppRegistry } = require("@cef-ebsi/app-jwt");
const provider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const tar = new TrustedAppRegistry(provider);
const decoded = await tar.verify(token);
console.log(decoded);
/*
{ iss: 'ebsi-wallet',
  aud: 'ebsi-ledger',
  iat: 1591892029,
  exp: 1591892044 }
*/

Check if an App is authorized

const { TrustedAppRegistry } = require("@cef-ebsi/app-jwt");
const provider = "https://api.intebsi.xyz/trusted-apps-registry/v1";
const tar = new TrustedAppRegistry(provider);
try {
  const auth = await tar.checkAuthorization("ebsi-ledger", "ebsi-wallet");
  console.log(auth);
} catch (error) {
  console.log(error);
}
/*
  true
*/

Utils

Utils contains a set of functions related to generation of private keys and verification of tokens.

Import utils

const { utils } = require("@cef-ebsi/app-jwt");

Read a private key as JWK

const key = utils.privateKeyAsJWK(PEMkey);

Create a random key in JWK

const key = utils.randomKey();

Check if headers follow EBSI standards

utils.checkHeaders(
  {
    alg: "ES256K",
    typ: "JWT",
  },
  { scope: "ebsi profile component" }
);
// true

Check if payload follows EBSI standards

utils.checkPayload({
  iss: "issuer",
  aud: "audience",
  iat: 10,
  exp: 25,
  nonce: "nonce", { scope: "ebsi profile entity" });

// force a specific audience to verify
utils.checkPayload({
  iss: "issuer",
  aud: "ebsi-wallet",
  iat: 10,
  exp: 25,
  nonce: "nonce", { scope: "ebsi profile entity", audience: "ebsi-wallet" });

Check headers and payload but not signature

utils.checkHeadersPayload(token);

// force a specific scope and audience
utils.checkHeadersPayload(token, {
  scope: "ebsi profile component",
  audience: "app",
});

Deduce scope looking into headers and payload

utils.deduceScope(token);

Verify that a token has been issued by a Trusted App and it is authorized to use the App described in the audience (for components and entities), or that the token has been signed using DIDs (for users).

utils.verify(token, {
  scope: "ebsi profile component",
  audience: "ebsi-wallet",
  tarProvider: "https://api.intebsi.xyz/trusted-apps-registry/v1",
  didResolver: didResolver,
});

Changes from previous version 0.0.3

The way to create and use methods in Agent and Session classes has changed.

  • Agent constructor: The scope must be defined in the constructor in order to determine the nature of the private key.
const agent = new Agent(Scope.COMPONENT, privKey, {
  issuer: "ebsi-wallet",
  expiration: { requestToken: 20 },
});
  • Agent createRequestPayload: This method does not require scope anymore and has changed to an async function, then requires await.
const request = await agent.createRequestPayload("api", opts);
  • Session constructor: The constructor now includes an optional argument for the DID resolver.
const session = new Session(
  apiName,
  apiPrivKey,
  provider,
  resolver,
  expiration
);
  • Session newSession: This method now has an optional argument to add more fields to the accessToken payload.
const extraPayload = { name: "eva" };
const result = await session.newSession(request, extraPayload);

Library Test

Create an .env file using .env.example and update the corresponding values.

# unit tests
$ yarn test

Licensing

Copyright (c) 2019 European Commission
Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in compliance with the Licence. You may obtain a copy of the Licence at:

Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence.

Readme

Keywords

none

Package Sidebar

Install

npm i @cef-ebsi/app-jwt

Weekly Downloads

2

Version

0.0.13

License

EUPL-1.2

Unpacked Size

76.6 kB

Total Files

43

Last publish

Collaborators

  • maurolucc
  • iamtxena
  • yhuard
  • joticajulian
  • zgorizzo