Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ overview of how the Box API handles authentication.
- [OAuth 2.0 Login (`box login`)](#oauth-20-login-box-login)
- [Option 1: Official Box CLI App](#option-1-official-box-cli-app)
- [Option 2: Your Own Platform App](#option-2-your-own-platform-app)
- [Option 3: Your Own Public Client App (PKCE)](#option-3-your-own-public-client-app-pkce)
- [Supported Ports](#supported-ports)
- [Additional Flags](#additional-flags)
- [Reauthorize OAuth2](#reauthorize-oauth2)
Expand Down Expand Up @@ -127,7 +128,7 @@ box configure:environments:add /path/to/config.json --ccg-auth --ccg-user "USER_

The `box login` command authenticates you with Box using OAuth 2.0. It starts a local callback server, opens your browser for authorization, and stores the resulting tokens in a named environment.

When you run `box login`, the CLI presents three options: the **Official Box CLI App**, a **Platform App** you create yourself, or **quit** (`q`) to exit. You can either choose interactively or skip the selection entirely using the `--default-box-app` (`-d`) flag. You can also paste a Client ID directly at the prompt — any input between 16 and 99 characters is treated as a Client ID.
When you run `box login`, the CLI presents four options: the **Official Box CLI App**, a **Platform App** you create yourself, a **public client app** you create yourself, or **quit** (`q`) to exit. You can either choose interactively or skip the selection entirely using the `--default-box-app` (`-d`) flag. You can also paste a Client ID directly at the prompt — any input between 16 and 99 characters is treated as a Client ID.

#### Option 1: Official Box CLI App

Expand All @@ -137,7 +138,7 @@ This is the fastest way to get started with Box CLI. No app creation in the Box

```bash
box login
# Choose [1] for Official Box CLI App, [2] for Platform App, or [q] to quit.
# Choose [1] for Official Box CLI App, [2] for Platform App, [3] for a public client app, or [q] to quit.
```

**Skip the prompt** — use the `--default-box-app` (or `-d`) flag to go directly to authorization:
Expand Down Expand Up @@ -172,6 +173,27 @@ box login

For a step-by-step walkthrough, see the [Quickstart Guide](https://developer.box.com/guides/tooling/cli/quick-start/).

#### Option 3: Your Own Public Client App (PKCE)

A command line tool can't keep a client secret confidential, so you can register your OAuth app as a **public client** instead. A public client has no client secret. Every login is protected with [PKCE](https://oauth.net/2/pkce/): the CLI creates a random code verifier, sends a challenge derived from it in the authorize URL, and presents the verifier when it exchanges the authorization code for tokens.

Before running the command, set up the app in the [Box Developer Console](https://cloud.app.box.com/developers/console):

1. Create a Custom App with **User Authentication (OAuth 2.0)** and choose the **public client** option. The app type can't be changed later, so an existing app with a client secret can't be turned into a public client.
2. In the **Configuration** tab, set the **Redirect URI** to `http://localhost:3000/callback` (adjust the port if you use a different `--port` value).
3. Click **Save Changes**.

Then log in and enter only the **Client ID**:

```bash
box login --public-client
# Or run "box login" and choose [3].
```

The environment is stored with `authMethod: oauth20` and `publicClient: true`, and no client secret. Access tokens are refreshed automatically with the refresh token, without a client secret. `box logout` and `box tokens:revoke` revoke tokens and `box tokens:exchange` downscopes them the same way.

To reauthorize a public client environment, run `box login --reauthorize --name <ENVIRONMENT_NAME>` without `--public-client`. The stored Client ID is reused and the login is again protected with PKCE. `--public-client` can't be combined with `--reauthorize`.

#### Supported Ports

The `box login` command starts a local callback server to receive the OAuth redirect. You can control the port with the `--port` (`-p`) flag. The default port is **3000**.
Expand All @@ -194,6 +216,7 @@ When using your own Platform App, any port can be used — just make sure the **
|------|-------|--------------------------------------------------------------------------------------|
| `--default-box-app` | `-d` | Use the Official Box CLI App and proceed directly to authorization. |
| `--platform-app` | | Skip the prompt and go directly to Platform App setup (Client ID and Client Secret). |
| `--public-client` | | Skip the prompt and go directly to public client app setup (Client ID only, PKCE). Can't be combined with `--reauthorize`. |
| `--port <number>` | `-p` | Set the port for the local callback server. Default: `3000`. |
| `--name <string>` | `-n` | Set a name for the environment. Default: `oauth`. |
| `--reauthorize` | `-r` | Reauthorize an existing environment (requires `--name`). |
Expand All @@ -220,7 +243,7 @@ To reauthorize, run:
box login --name "ENVIRONMENT_NAME" --reauthorize
```

The `--reauthorize` flag retrieves the existing `clientID` and `clientSecret` from the stored environment, so you do not need to enter them again. After a successful login, the environment is updated and set as the default.
The `--reauthorize` flag retrieves the existing `clientID` and `clientSecret` (or, for a public client app, just the `clientID`) from the stored environment, so you do not need to enter them again. After a successful login, the environment is updated and set as the default.

You can also combine `--reauthorize` with `--default-box-app` to switch an existing environment to the Official Box CLI App:

Expand Down
17 changes: 16 additions & 1 deletion docs/login.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ Login options:
(2) Your own Platform OAuth App
Enter your Client ID and Client Secret when prompted. Use --platform-app to skip the prompt.

(3) Your own Platform OAuth public client App
For apps registered as a public client, which have no client secret. Enter your Client ID when prompted; the login is protected with PKCE. Use --public-client to skip the prompt.

Quickstart: run "box login -d" to sign in immediately. A browser window will open for authorization. Once access is granted, the environment is created and set as default — you can start running commands right away.

Headless environments: use --code (-c) if no browser is available. The CLI will display an authorize URL — visit it in an external browser, authorize and grant access to the app, then provide the state and authorization code back to the CLI when prompted.
Expand All @@ -23,7 +26,8 @@ Sign in with OAuth 2.0 and create a new environment (or update an existing one w

```
USAGE
$ box login [--no-color] [-h] [-v] [-q] [-c] [-p <value>] [-d | --platform-app] [-r -n <value>] [-i]
$ box login [--no-color] [-h] [-v] [-q] [-c] [-p <value>] [-d | --platform-app | --public-client] [-r -n
<value>] [-i]

FLAGS
-c, --code
Expand Down Expand Up @@ -65,6 +69,13 @@ FLAGS
Skip the authentication method prompt and go directly to Platform App setup.
You will be prompted for Client ID and Client Secret.

--public-client
Skip the authentication method prompt and go directly to public client app setup.
Use this for an OAuth 2.0 app registered in the Developer Console as a public client, which has no client secret.
Every login is protected with PKCE. You will be prompted for the Client ID only.
Cannot be combined with --reauthorize. To reauthorize a public client environment, run "box login --reauthorize
--name <ENVIRONMENT_NAME>".

DESCRIPTION
Sign in with OAuth 2.0 and create a new environment (or update an existing one with --reauthorize).

Expand All @@ -76,6 +87,10 @@ DESCRIPTION
(2) Your own Platform OAuth App
Enter your Client ID and Client Secret when prompted. Use --platform-app to skip the prompt.

(3) Your own Platform OAuth public client App
For apps registered as a public client, which have no client secret. Enter your Client ID when prompted; the login is
protected with PKCE. Use --public-client to skip the prompt.

Quickstart: run "box login -d" to sign in immediately. A browser window will open for authorization. Once access is
granted, the environment is created and set as default — you can start running commands right away.

Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@oclif/table": "0.5.4",
"@octokit/rest": "^22.0.0",
"archiver": "^8.0.0",
"bluebird": "^3.7.2",
"box-node-sdk": "^4.11.1",
"chalk": "^2.4.1",
"cli-progress": "^2.1.0",
Expand Down
135 changes: 133 additions & 2 deletions src/box-command.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ const BoxTSSDK = require('box-node-sdk/sdk-gen');
const BoxTsErrors = require('box-node-sdk/sdk-gen/box/errors');
const BoxCLIError = require('./cli-error');
const CLITokenCache = require('./token-cache');
const PublicClientSessionAdapter = require('./public-client-session-adapter');
const {
isPublicClientEnvironment,
createPublicClientTsClient,
createReauthorizeError,
isRefreshTokenRejectedError,
} = require('./public-client');
const PaginationUtilities = require('./pagination-utils');
const utils = require('./util');
const pkg = require('../package.json');
Expand Down Expand Up @@ -67,6 +74,7 @@ const KEY_MAPPINGS = {
defaultAsUserId: 'Default As-User ID',
useDefaultAsUser: 'Use Default As-User',
cacheTokens: 'Cache Tokens',
publicClient: 'Public Client',
ip: 'IP',
operationParams: 'Operation Params',
copyInstanceOnItemCopy: 'Copy Instance On Item Copy',
Expand Down Expand Up @@ -115,6 +123,24 @@ function getDebugErrorDetails(error) {
};
}

/**
* Build the CLI error message for a TS SDK API error response.
* OAuth2 token endpoint errors use `error` and `error_description` instead of the regular API error fields.
*
* @param {Object} responseInfo The response info of a BoxApiError
* @returns {string} The error message
*/
function formatApiErrorMessage(responseInfo) {
const body = responseInfo.body;
if (typeof body.error !== 'string') {
return `Unexpected API Response [${body.status} ${body.message} | ${body.request_id}] ${body.code} - ${body.message}`;
}
const message = `Unexpected API Response [${responseInfo.statusCode}] ${body.error}`;
return body.error_description
? `${message} - ${body.error_description}`
: message;
}

/**
* Parse a string value from CSV into the correct boolean value
* @param {string|boolean} value The value to parse
Expand Down Expand Up @@ -811,6 +837,11 @@ class BoxCommand extends Command {
client = ccgUser
? sdk.getCCGClientForUser(ccgUser)
: sdk.getAnonymousClient();
} else if (isPublicClientEnvironment(environment)) {
client = await this._createPublicClientLegacyClient(
environmentsObj.default,
environment
);
} else if (
environmentsObj.default &&
environmentsObj.environments[environmentsObj.default].authMethod ===
Expand Down Expand Up @@ -994,6 +1025,11 @@ class BoxCommand extends Command {
auth: ccgAuth,
});
client = this._configureTsSdk(client, SDK_CONFIG);
} else if (isPublicClientEnvironment(environment)) {
client = this._getPublicClientTsClient(
environmentsObj.default,
environment
);
} else if (
environmentsObj.default &&
environmentsObj.environments[environmentsObj.default].authMethod ===
Expand Down Expand Up @@ -1097,6 +1133,88 @@ class BoxCommand extends Command {
return client;
}

/**
* Create the legacy SDK client for a public client (PKCE) environment.
*
* The legacy SDK only supports OAuth with a client secret, so the client's
* session is replaced with an adapter that gets tokens from the generated
* SDK auth. Token requests use the TS client's network session, so they
* honor the same proxy, base URL and header settings as the TS client.
*
* @param {string} environmentName Name of the current environment
* @param {Object} environment The current environment
* @returns {Promise<BoxClient>} The legacy SDK client
* @private
*/
async _createPublicClientLegacyClient(environmentName, environment) {
DEBUG.init(
'Using public client environment %s %O',
environmentName,
environment
);
const tsClient = this._getPublicClientTsClient(
environmentName,
environment
);
const cachedToken = await this._publicClientAuth.tokenStorage.get();
if (!cachedToken?.accessToken) {
throw createReauthorizeError(environmentName);
}
const sdk = new BoxSDK({
clientID: environment.clientId,
clientSecret: '',
...SDK_CONFIG,
});
this._configureSdk(sdk, { ...SDK_CONFIG });
this.sdk = sdk;

const client = sdk.getBasicClient('');
client._session = new PublicClientSessionAdapter(
this._publicClientAuth,
{
environmentName,
expiryBufferMS: sdk.config.expiredBufferMS,
networkSession: tsClient.networkSession,
// Already read to check the environment is logged in, so the adapter does not read it again
initialToken: cachedToken,
}
);
return client;
}

/**
* Get the TS SDK client for a public client (PKCE) environment.
* Built once per command, so the legacy and TS clients share one auth and token cache.
*
* @param {string} environmentName Name of the current environment
* @param {Object} environment The current environment
* @returns {BoxTSSDK.BoxClient} The configured TS SDK client
* @private
*/
_getPublicClientTsClient(environmentName, environment) {
if (!this._publicClientTsClient) {
// Public client tokens are always cached: without the refresh token every command would need a new login.
this._publicClientEnvironmentName = environmentName;
const { auth, client } = createPublicClientTsClient(this, {
clientId: environment.clientId,
tokenStorage: new CLITokenCache(environmentName),
});
this._publicClientAuth = auth;
this._publicClientTsClient = client;
}
return this._publicClientTsClient;
}

/**
* Whether this command authenticates with the public client (PKCE) auth of the current environment.
* Only meaningful after client setup.
*
* @returns {boolean} True for public client environments not overridden by --token
*/
usesPublicClientAuth() {
return Boolean(this._publicClientAuth);
}

/**
* Configures SDK by using values from settings.json file
* @param {*} sdk to configure
Expand Down Expand Up @@ -1684,13 +1802,26 @@ class BoxCommand extends Command {
const AUTH_FAILED_HINT =
'Authentication failed: token is invalid or expired. OAuth: run "box login --reauthorize". JWT/CCG: tokens are refreshed automatically, so a 401 usually means app credentials or environment configuration must be fixed. You can also provide a fresh token with --token.';
if (
this.usesPublicClientAuth() &&
err instanceof BoxTsErrors.BoxApiError &&
isRefreshTokenRejectedError(err)
) {
// The TS SDK refreshes on 401 and surfaces the token endpoint error when the refresh token is no longer valid.
err = createReauthorizeError(
this._publicClientEnvironmentName,
err
);
} else if (
err instanceof BoxTsErrors.BoxApiError &&
err.responseInfo &&
err.responseInfo.body
) {
const responseInfo = err.responseInfo;
let errorMessage = `Unexpected API Response [${responseInfo.body.status} ${responseInfo.body.message} | ${responseInfo.body.request_id}] ${responseInfo.body.code} - ${responseInfo.body.message}`;
if (responseInfo.body.status === 401) {
let errorMessage = formatApiErrorMessage(responseInfo);
if (
responseInfo.body.status === 401 ||
responseInfo.statusCode === 401
) {
errorMessage += `\n${AUTH_FAILED_HINT}`;
}
err = new BoxCLIError(errorMessage, err);
Expand Down
Loading
Loading