Authentication with JWT

Box offers an authentication model that lets applications authenticate directly to Box using JWT authentication.

This authentication method is meant for server-to-server applications. It replaces the first leg of the standard 3-legged OAuth 2.0 process, where users grant an application authorization to access their Box account.

This guide will take you through the steps to authenticate using OAuth 2.0 with JWT. If you have not already configured your application for Box Platform, please complete this tutorial.

Overview

OAuth 2.0 with JWT allows your application to request OAuth 2.0 access tokens necessary to make calls to the Box Content API. Your application may request one of two token types: an enterprise access token and a user access token.

  • Enterprise access token: Used to provision users via the /users endpoint.
  • User access token: Used to make API calls to endpoints of the Content API.

Creating App Users and Managing Your Enterprise

When an application is created in the Box Developer Console, a Service Account is created. Service Accounts are a user-based representation of your app within a Box Enterprise (EID). Using the Service Account, you can obtain an enterprise access token.

Using the enterprise access token, you can create new App Users for your enterprise, as well as manage groups and other enterprise settings. To request this token, you will need to specify the associated enterprise ID. This can be found in the Admin Console under the Account Info tab. You will only be able to access this tab if you are the Admin of the account.

Performing User-Based Actions

Once you have created an App User, you can then request a user access token via the App Auth feature, which will return the OAuth2 access token for the specified user. This token is used to take user-specific actions (e.g., upload/download content, make comments, assign tasks, share with other users, etc.).

Your service will authenticate to Box by sending a JSON Web Token to the /token endpoint containing a JSON payload that includes the Client ID, enterprise_id or user_id, and additional claims, and sign it using the private key of an RSA keypair. Box then verifies the identity of your application using the public key specific to your application.

1. Generate an RSA Keypair in the Developer Console

The first step is to create an RSA private-public keypair used to sign and authenticate the JSON Web Token (JWT) assertion. The private key is used to sign your requests and is verified by the public key, which you provide to Box. Be sure to protect your private key as this is the only means to verify your application's identity.

Box offers the ability to automatically create your own RSA keypair through the developer console. We do not store the private key generated, so remember to keep note of it. In order to do this:

  • Navigate to the configuration page for your application
  • Scroll down to Add and Manage Public Keys
  • Select Generate a Public/Private Keypair

Box will generate your public/private key pair, upload the public key to our system and then download a JSON file with your private key and application settings. Note that the downloaded private key is encrypted, and you must decrypt it using the passphrase provided in the JSON before use.

You can also generate your own RSA key pair. The instructions for that process are available here.

2. Grant Access to Your Application in Enterprise Admin Console

In order to begin creating App Users in an enterprise, authorization for your application must be granted in the Enterprise Admin console. If you are building with your own developer enterprise, follow the instructions below.

  1. Log in to Box and select Admin Console at the top of the screen.
  2. Go to the Enterprise Settings and click on Apps.
  3. Within the Custom Applications section, choose Authorize New App.
  4. Enter the Client ID for the app you would like to enable. This will display the requested Applications Scopes and User Access Level* that determines which users the app has control over. The determine what permissions an Application receives in the enterprise and which sets of users an application may access and modify.
  5. Once Authorized, the app will be enabled within your Developer enterprise.

3. Generate an Enterprise Access Token with Box SDKs

Now that you have generated your JWT credentials, you can use one of the Box SDKs to generate an enterprise access token.

The enterprise access token will let you make calls as a service account.

Box SDK Examples

We will authenticate with the JWT credentials that were automatically generated by the Box developer console. We'll generate a token by providing the path to the file with those credentials. With the enterprise access token, we will make a call to the Users endpoint to get information about the current user.

Let's walk through how to do this with the Box .NET, Java, and Node SDKs.

using System;
using System.IO;
using System.Threading.Tasks;
using Box.V2;
using Box.V2.Config;
using Box.V2.JWTAuth;

namespace BoxPlayground
{
    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Create an async method to execute and await Box SDK methods.
                ExecuteMainAsync().Wait();
            }
            catch (Exception ex)
            {
                // Log any errors for debugging 
                Console.WriteLine(ex);
            }
        }
        
        private static async Task ExecuteMainAsync()
        {
            // Open a stream to read and dispose of the automatically created Box configuration file.
            using (FileStream fs = new FileStream($"./config.json", FileMode.Open))
            {
                // Initialize the SDK with the Box configuration file and create a client that uses the Service Account.
                var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs));
                var serviceAccountClient = session.AdminClient(session.AdminToken());
                
                // Use the GetCurrentUserInformationAsync method to retrieve current user's information.
                // Since this client uses the Service Account, this will return the Service Account's information.
                var serviceAccountUserInfo = await serviceAccountClient.UsersManager.GetCurrentUserInformationAsync();
                // Log the Service Account's login value which should contain "AutomationUser". 
                // For example, AutomationUser_375517_dxVhfxwzLL@boxdevedition.com
                Console.WriteLine(serviceAccountUserInfo.Login);
            }
        }
    }
}
package com.boxplayground;
import com.box.sdk.*;
import java.io.FileReader;
import java.io.Reader;

public class App {
    public static void main( String[] args ) {
        // Open a reader to read and dispose of the automatically created Box configuration file.
        try(Reader reader = new FileReader("src/config/config.json")) {
            // Initialize the SDK with the Box configuration file and create a client that uses the Service Account.
            BoxConfig boxConfig = BoxConfig.readFrom(reader);
            BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig);
            
            // Use the getCurrentUser method to retrieve current user's information.
            // Since this client uses the Service Account, this will return the Service Account's information.
            BoxUser serviceAccountUser = BoxUser.getCurrentUser(serviceAccountClient);
            BoxUser.Info serviceAccountUserInfo = serviceAccountUser.getInfo();
            // Log the Service Account's login value which should contain "AutomationUser". 
            // For example, AutomationUser_375517_dxVhfxwzLL@boxdevedition.com
            System.out.println(serviceAccountUserInfo.getLogin());
        } catch (java.io.IOException e) {
            // Log any errors for debugging 
            e.printStackTrace();
        }
    }
}
'use strict';
// Require the Box SDK and the fs module
const box = require('box-node-sdk');
const fs = require('fs');

// Read and parse the automatically created Box configuration file.
let configFile = fs.readFileSync('config.json');
configFile = JSON.parse(configFile);

// Initialize the SDK with the Box configuration file and create a client that uses the Service Account.
let session = box.getPreconfiguredInstance(configFile);
let serviceAccountClient = session.getAppAuthClient('enterprise');

// Use the users.get method to retrieve current user's information by passing 'me' as the ID.
// Since this client uses the Service Account, this will return the Service Account's information.
serviceAccountClient.users.get('me', null)
    .then((serviceAccountUser) => {
        // Log the Service Account's login value which should contain "AutomationUser". 
        // For example, AutomationUser_375517_dxVhfxwzLL@boxdevedition.com
        console.log(serviceAccountUser.login)
    })
    .catch((err) => {
        // Log any errors for debugging 
        console.log(err);
    });

Additional Notes

  • If you decide not to use the RSA key pair auto-generation feature of the Box developer console, you can manually generate your own RSA key pair and upload your public key to Box. The instructions for that process are available here.
  • If you decide not to use one of the Box SDKs, you can construct the JWT claim manually. This page documents those steps.
  • Multiple access tokens can be live at any given time and the expiration for each token is independent of the expiration of any other access tokens.

Next Steps

You have now successfully set up your app's authentication, created a Service Account, and are ready to create your first App User. Complete the next tutorial to learn how to create your first App User and make your first API call.

Questions
If you have any questions, please visit our developer forum.

Authentication with JWT