Authenticate Box node.js SDK with JWT

Olga Stefaniuk
Box Developer Blog
Published in
6 min readJul 11, 2023

In my previous post, I explored the topic of Box Node.js authentication with OAuth 2.0. Now let’s jump into another method that includes JWT, server-side authentication. It is the most common way to authenticate to the Box API.

JWT is an open standard designed to allow powerful server-to-server authentication.

When to use JWT?

Server-side authentication with JWT is the ideal authentication method for apps that:

  • Work with users who don’t have a Box account.
  • Want to use their own identity system.
  • Don’t want users to have to know that they are using Box
  • Want to store data within the application’s Box account (Service Account) and not within the user’s Box account

Steps to create the app

  1. Create a Custom Box Application
  2. Generate a keypair and download the JSON configuration
  3. Authorise the app in the Admin Console
  4. Initialize the project and the SDK client
  5. Get a file’s information using the SDK client

1. Create a Custom Box Application

Prerequisites: Node.js, a free Box developer account

In the Developer Console, click Create App and choose Custom App.

Developer Console view: Create a Custom App flow

Next, a popup will appear, and you’ll be asked to fill out the app name, a short description, and the purpose of your app (in this case, it might be an integration).

In the last field, choose Customer if you are a Box customer or Partner if you are building the application to be used outside of your organisation.

Developer Console view: Create a Custom App flow

In the second step, choose Server Authentication (with JWT) and create the app. Once created, let’s go to the app Configuration tab.

2. Generate a keypair and download the JSON configuration

To generate the keypair, navigate to the Configuration tab of the Developer Console and scroll down to the section called Add and Manage Public Keys.

Developer Console view: Add and Manage Public Keys

Click Generate a Public/Private Keypair; this action triggers the download process of the config.json file, which will be needed in a short while. For security purposes, for this action, your Box account will need to have 2FA enabled.

ℹ️ You may interact with Box using the SDK in several ways. The default one is with the Service Account. The Service Account is a separate application’s Box account that has its own folder structure and permissions. In the General Settings tab, you can check your Service Account email address. For more information, check out our User Types guide.

Developer Console view: Service Account ID in the General Settings tab

3. Authorise the app in the Admin Console

Now, let’s authorise the newly created Box app. In the Developer Console, go to the Authorization tab and click the Review and Submit button. A notification email will be sent to the Box Enterprise Admin.

Developer Console view: request Custom App Authorization

In the Admin Console, go to the Apps section and choose the Custom Apps Manager. There, you’ll be able to authorise the new custom Box app. For a detailed description of the process, see our Custom App Approval guide.

Admin Console view: Custom Apps Approval process

4. Initialize the project and the SDK client

Let’s finally begin the coding part. If you’re working on a brand new project, open a terminal, create a new directory, and navigate into it:

mkdir box-node-sdk-jwt
cd box-node-sdk-jwt

Initialize a new project:

npm init

Install the Box Node.js SDK:

npm install --save box-node-sdk

Make sure you include in the project directory the config.json file downloaded from the Developer Console. It should look like the example below and include values specific to your app:

{
"boxAppSettings": {
"clientID": "abc...123",
"clientSecret": "def...234",
"appAuth": {
"publicKeyID": "abcd1234",
"privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\n....\n-----END ENCRYPTED PRIVATE KEY-----\n",
"passphrase": "ghi...345"
}
},
"enterpriseID": "1234567"
}

Next, create the index.js file and require the config.json and Box SDK. Finally, let’s initialise the SDK.

const config = require('./config.json');
const BoxSDK = require('box-node-sdk');

const sdk = BoxSDK.getPreconfiguredInstance(config);
const client = sdk.getAppAuthClient('enterprise');

5. Get a file’s information using the SDK client

As mentioned, we’ll be using the default settings and accessing the content stored in Box using the Service Account.

ℹ️ If you need to perform actions on behalf of a specific user, read this guide for more details.

You can check the Service Account ID in the Configuration tab in the Developer Console, or you may also log more details in your terminal by adding a request in your index.js file.

// continue the index.js file

client.users.get(client.CURRENT_USER_ID)
.then(currentUser => {
console.log(currentUser)
});

Let’s check if the SDK is properly authenticated by running it in your terminal:

node index.js

You should get a bunch of details related to the Service Account like account type, id, name, login, and more.

ℹ️ By default, most Service Accounts are allocated 10GB of storage. You can update the amount of storage allocated to a Service Account by making an API call to the update user endpoint and passing in the desired value in bytes using the space_amount body parameter.

Additionally, depending on the granted scopes, a Service Account may have the ability to perform Admin actions.

To grant access for the Service Account to a certain file or folder stored in Box, you can do it directly in the web app.

Box web app view: sharing a file with a Service Account

Once the file is shared with the Service Account we can perform the get file’s information request. The file or folder ID can be found in the URL in the Box web app.

https://app.box.com/folder/{folderID}
https://app.box.com/file/{fileID}

Replace the fileID with the accurate value.

// continue the index.js file

client.files.get('fileID')
.then(file => {
console.log(file)
});

Let’s run the script in the terminal again:

node index.js

Voila! ✨ That’s your first file request using the Box node.js SDK! Check the SDK documentation for additional options for this action.

{
type: 'file',
id: '11111',
file_version:
{ type: 'file_version',
id: '22222',
sha1: 'exampleValue' },
sequence_id: '1',
etag: '1',
sha1: 'exampleValue',
name: 'file.png',
description: '',
size: 106833,
path_collection:
{ total_count: 2,
entries:
[ { type: 'folder',
id: '0',
sequence_id: null,
etag: null,
name: 'All Files' },
{ type: 'folder',
id: '33333',
sequence_id: '0',
etag: '0',
name: 'Collaborated Folder' } ] },
created_at: '2016-11-16T22:01:44-08:00',
modified_at: '2016-11-16T22:01:51-08:00',
trashed_at: null,
purged_at: null,
content_created_at: '2016-10-29T18:33:50-07:00',
content_modified_at: '2016-10-29T18:33:50-07:00',
created_by:
{ type: 'user',
id: '44444',
name: 'Owner',
login: 'owner@example.com' },
modified_by:
{ type: 'user',
id: '44444',
name: 'Owner',
login: 'owner@example.com' },
owned_by:
{ type: 'user',
id: '44444',
name: 'Owner',
login: 'owner@example.com' },
shared_link: null,
parent:
{ type: 'folder',
id: '33333',
sequence_id: '0',
etag: '0',
name: 'Collaborated Folder' },
item_status: 'active'
}

Now, go beyond!

📚 Read Box node.js SDK documentation!

💻 Build a custom user facing app; first check the additional CORS configuration in the Developer Console.

📥 / 📤 Download or upload a file using the SDK; remember to adjust application scope settings in the Developer Console.

🔑 Check out a sample app with Box node.js and the OAuth 2.0 authentication method in my previous blog post.

🦄 Want to learn from Box Platform champions?

Join our Box Developer Community for support and knowledge sharing!

Cheers!

--

--