The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's developer console page.
To create a BoxClient
with a developer token, construct an BoxDeveloperTokenAuth
object with the token
set to the developer token and construct the client with that.
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxDeveloperTokenAuth,
} = require('box-typescript-sdk-gen/lib/developerTokenAuth.generated.js');
const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' });
const client = new BoxClient({ auth });
const me = await client.users.getUserMe();
console.log(`My user ID is ${me.id}`);
Before using JWT Auth make sure you set up correctly your Box App. The guide with all required steps can be found here: Setup with JWT
JWT auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a Service Account that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa.
If you generated your public and private keys automatically through the
Box Developer Console, you can use the JSON file created there
to configure your SDK instance and create a client to make calls as the
Service Account. Call one of static BoxJwtAuth
method:
JwtConfig.fromConfigFile(configFilePath)
and pass JSON file local path
or JwtConfig.fromConfigJsonString(configJsonString)
and pass JSON config file content as string.
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxJwtAuth,
JwtConfig,
} = require('box-typescript-sdk-gen/lib/jwtAuth.generated.js');
const jwtConfig = JwtConfig.fromConfigFile('/path/to/settings.json');
const jwtAuth = new BoxJwtAuth({ config: jwtConfig });
const client = new BoxClient({ auth: jwtAuth });
const me = await client.users.getUserMe();
console.log(`My user ID is ${me.id}`);
Otherwise, you'll need to provide the necessary configuration fields directly to the JwtConfig
constructor:
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxJwtAuth,
JwtConfig,
} = require('box-typescript-sdk-gen/lib/jwtAuth.generated.js');
const jwtConfig = new JwtConfig({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
jwtKeyId: 'YOUR_JWT_KEY_ID',
privateKey: 'YOUR_PRIVATE_KEY',
privateKeyPassphrase: 'PASSPHRASE',
enterpriseId: 'YOUR_ENTERPRISE_ID',
});
const jwtAuth = new BoxJwtAuth({ config: jwtConfig });
const serviceAccountClient = new BoxClient({ auth: jwtAuth });
App auth applications also often have associated App Users, which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the API documentation for detailed instructions on how to use app auth.
Clients for making calls as an App User can be created with the same JSON JWT config file generated through the
Box Developer Console. Calling jwtAuth.withUserSubject('USER_ID')
method will return a new auth object,
which is authenticated as the user with provided id, leaving the original object unchanged.
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxJwtAuth,
JwtConfig,
} = require('box-typescript-sdk-gen/lib/jwtAuth.generated.js');
const jwtConfig = JwtConfig.fromConfigFile('/path/to/settings.json');
const jwtAuth = new BoxJwtAuth({ config: jwtConfig });
const userAuth = jwtAuth.withUserSubject('USER_ID');
const userClient = new BoxClient({ auth: userAuth });
Alternatively, clients for making calls as an App User can be created with the same JwtConfig
constructor as in the above examples, similarly to creating a Service Account client. Simply pass the
userId
instead of enterpriseId
when constructing the auth config instance:
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxJwtAuth,
JwtConfig,
} = require('box-typescript-sdk-gen/lib/jwtAuth.generated.js');
const jwtConfig = new JwtConfig({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
jwtKeyId: 'YOUR_JWT_KEY_ID',
privateKey: 'YOUR_PRIVATE_KEY',
privateKeyPassphrase: 'PASSPHRASE',
userId: 'USER_ID',
});
const jwtAuth = new BoxJwtAuth({ config: jwtConfig });
const userClient = new BoxClient({ auth: jwtAuth });
Before using Client Credentials Grant Auth make sure you set up correctly your Box App. The guide with all required steps can be found here: Setup with Client Credentials Grant
Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account.
You can use CCGAuth
to initialize a client object the same way as for other authentication types:
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxCcgAuth,
CcgConfig,
} = require('box-typescript-sdk-gen/lib/ccgAuth.generated.js');
const ccgConfig = new CcgConfig({
userId: 'YOUR_USER_ID',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
});
const ccgAuth = new BoxCcgAuth({ config: ccgConfig });
const client = new BoxClient({ auth: ccgAuth });
const me = await client.users.getUserMe();
console.log(`My user ID is ${me.id}`);
Obtained token is valid for specified amount of time, it will be refreshed automatically by default.
The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret:
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxCcgAuth,
CcgConfig,
} = require('box-typescript-sdk-gen/lib/ccgAuth.generated.js');
const ccgConfig = new CcgConfig({
enterpriseId: 'YOUR_ENTERPRISE_ID',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
});
const ccgAuth = new BoxCcgAuth({ config: ccgConfig });
const client = new BoxClient({ auth: ccgAuth });
In order to enable obtaining user token you have to go to your application configuration that can be found
here. In Configuration
tab, in section Advanced Features
select Generate user access tokens
. Do not forget to re-authorize application if it was already authorized.
To obtain user account you will have to provide user ID with client id and secret.
const { BoxClient } = require('box-typescript-sdk-gen/lib/client.generated.js');
const {
BoxCcgAuth,
CcgConfig,
} = require('box-typescript-sdk-gen/lib/ccgAuth.generated.js');
const ccgConfig = new CcgConfig({
userId: 'YOUR_USER_ID',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
});
const ccgAuth = new BoxCcgAuth({ config: ccgConfig });
const client = new BoxClient({ auth: ccgAuth });
You can easily switch to be authenticated as a Service Account or as a User. To create a new auth object authenticated as Service Account you can call:
const enterpriseAuth = ccgAuth.withEnterpriseSubject('YOUR_ENTERPRISE_ID');
const enterpriseClient = new BoxClient({ auth: enterpriseAuth });
To authenticate with user subject call:
const userAuth = ccgAuth.withUserSubject('YOUR_USER_ID');
const userClient = new BoxClient({ auth: userAuth });
The new token will be automatically fetched with a next API call.
If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the Authentication with OAuth API documentation.
Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code.
const {
BoxOAuth,
OAuthConfig,
} = require('box-typescript-sdk-gen/lib/oauth.generated.js');
const config = new OAuthConfig({
clientId: 'OAUTH_CLIENT_ID',
clientSecret: 'OAUTH_CLIENT_SECRET',
});
const oauth = new BoxOAuth({ config: config });
// the URL to redirect the user to
var authorize_url = oauth.getAuthorizeUrl();
After a user logs in and grants your application access to their Box account,
they will be redirected to your application's redirect_uri
which will contain
an auth code. This auth code can then be used along with your client ID and
client secret to establish an API connection.
You need to provide the auth code to the SDK to obtain an access token, then you can use the SDK as usual.
await oauth.getTokensAuthorizationCodeGrant('code');
Access tokens for a client can be revoked when needed. This call invalidates old token.
For CCGAuth and JWTAuth you can still reuse the auth
object to retrieve a new token. If you make any new call after revoking the token,
a new token will be automatically retrieved.
For OAuth it would be necessary to manually go through the authentication process again.
To revoke current client's tokens in the storage use the following code:
await auth.revokeTokens();
// client's tokens have been revoked
You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app).
A downscoped token does not include a refresh token. In such a scenario, to obtain a new downscoped token, refresh the original token and utilize the newly acquired token to obtain the downscoped token.
More information about downscoping tokens can be found here. If you want to learn more about available scopes please go here.
For example to get a new token with only item_preview
scope, restricted to a single file, suitable for the
Content Preview UI Element you can use the following code.
You can also initialize DeveloperTokenAuth
with the retrieved access token and use it to create a new Client.
let resource = 'https://api.box.com/2.0/files/123456789';
let token = await oauth.downscopeToken(['item_preview'], resource);
const auth = new BoxDeveloperTokenAuth({ token: token.accessToken });
const client = new BoxClient({ auth });
By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for OAuth:
const config = new OAuthConfig({
clientId: 'OAUTH_CLIENT_ID',
clientSecret: 'OAUTH_CLIENT_SECRET',
});
const oauth = new BoxOAuth({ config: config });
You can also provide a custom token storage class. All you need to do is create a class that implements TokenStorage
interface and pass an instance of your class to the AuthConfig constructor.
const config = new OAuthConfig({
clientId: 'OAUTH_CLIENT_ID',
clientSecret: 'OAUTH_CLIENT_SECRET',
tokenStorage: new MyCustomTokenStorage(),
});
const oauth = new BoxOAuth({ config: config });