Skip to content

Getting a session token from the API

<pdf-application> and session tokens

The <pdf-application> component is responsible for the authentication against the api. It manages the session that stores the credentials.

You can provide your api keys as properties to the <pdf-application> component. This is however not recommended for production usage.

⚠️ Security consideration

To keep your api keys secure you should not inject them in the frontend in your production environment. Everything in the frontend can be made visible to browser users and this would expose your secrets.

If no api keys are not provided as properties, then the <pdf-application> component expects an endpoint /api/session on the web host. This endpoint should return a valid session token. You can use the UnoPDF /v1/sessions endpoint to create a token.

Creating a token from the command line

You can get a session token by doing a POST call to https://api.unopdf.com/v1/sessions and supplying your publickey and privatekey as a JSON body. Replace <publickey> and <privatekey> with your own keys in the sample below.

shell
curl 'https://api.unopdf.com/v1/sessions' \
-X 'POST' \
-H 'Content-Type: application/json' \
--data-binary '{"publickey":"<publickey>","privatekey":"<privatekey>"}'

Creating a token - Nodejs

ts
const response = await fetch('https://api.unopdf.com/v1/sessions', {
    "method": "POST",
    "headers": { "Content-Type": "application/json" },
    "body": JSON.stringify({ publickey: "<publickey>", privatekey: "<privatekey>" }),
});

See below for a full sample.

Code

ts
import dotenv from "dotenv";
dotenv.config();

import { getError } from "./errorhandling";

async function getToken(): Promise<string> {
  const api_url = process.env.UNOPDF_API_URL;
  const privatekey = process.env.UNOPDF_PRIVATE_KEY;
  const publickey = process.env.UNOPDF_PUBLIC_KEY;

  const method = "POST";
  const headers = { "Content-Type": "application/json" };
  const body = JSON.stringify({ publickey, privatekey });
  const url = `${api_url}/v1/sessions`;
  
  const response = await fetch(url, {
    method,
    headers,
    body,
  });

  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "${method} ${url}".`);
  }

  const json = await response.json();
  if (typeof json !== "string") {
    throw new Error(`Unexpected response "${json}" from UnoPdf API "${method} ${url}".`);
  }

  return json;
}

getToken().then((token) => console.log(token));

Running the example

  • Download the rest - Getting a session token from the API project
  • Unzip the file to a directory rest-get-token.
    shell
    unzip rest-get-token.zip -d rest-get-token
  • Open a terminal and go to that directory
    shell
    cd rest-get-token
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start