DEV Community

Cover image for Get Kontent Project ID from the Management API key
Ondřej Chrastina for Kontent.ai

Posted on • Originally published at ondrej.chrastina.tech

Get Kontent Project ID from the Management API key

It is possible to parse out Kontent Project ID out of the Management API Key. That means no more necessity to ask for two keys for your Kontent tools.

Do you develop any Kontent tool using Management API and still ask for both - Project ID and Management API key? Following lines will help you to improve your UX as well as cleanout your code.

The management API key is just a JWT token containing the payload (in between header with signature). So you could decode it i.e. by using JWT.io, And as a payload, you could see this:

{
    "jti": "b6a9ee86bfdc41c89f20048c3baaba04",
    "iat": "1612535158",
    "exp": "1958135158",
    "project_id": "06c2b8951700013e5f3160283aff1100",
    "ver": "2.1.0",
    "uid": "usr_0vMrpCH2TkOK5oK3y3bKNS",
    "aud": "manage.kenticocloud.com"
}
Enter fullscreen mode Exit fullscreen mode

The project_id could be used to identify the project with one modification. It is necessary to add dashes on appropriate places to respect the GUID format.

To do all of that, the code would end up looking like that (or any other language alternative) - or you just use a library like jwt-decode. But it is always good to know what they do.

const managementApiKey = "ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAianRpIjogImI2YTllZTg2YmZkYzQxYzg5ZjIwMDQ4YzNiYWFiYTA0IiwNCiAgImlhdCI6ICIxNjEyNTM1MTU4IiwNCiAgImV4cCI6ICIxOTU4MTM1MTU4IiwNCiAgInByb2plY3RfaWQiOiAiMDZjMmI4OTUxNzAwMDEzZTVmMzE2MDI4M2FmZjExMDAiLA0KICAidmVyIjogIjIuMS4wIiwNCiAgInVpZCI6ICJ1c3JfMHZNcnBDSDJUa09LNW9LM3kzYktOUyIsDQogICJhdWQiOiAibWFuYWdlLmtlbnRpY29jbG91ZC5jb20iDQp9.aEqGajw7e9m13lnID0z9PBCL0MytqYlvoYg_rwPfEJo";

const payloadBase64 = managementApiKey.split('.')[1];
const payloadBase64Cleared = payloadBase64.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
    atob(payloadBase64Cleared)
    .split('')
    .map((c) => 
        ('%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
    )
    .join('')
);

const payloadObject = JSON.parse(jsonPayload);

const projectIdWithoutDashes = payloadObject.project_id;

const projectId = 
    `${projectIdWithoutDashes.substr(0, 8)}-\
${projectIdWithoutDashes.substr(8, 4)}-\
${projectIdWithoutDashes.substr(12,4 )}-\
${projectIdWithoutDashes.substr(16, 4)}-\
${projectIdWithoutDashes.substr(20)}`

console.log(projectId);
Enter fullscreen mode Exit fullscreen mode

If you want to play with it - check out this Codepen.

...and of course, I invalidated the showcased API key 🤞

Latest comments (0)