Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.5.0+

Box: Get a Service Account Token with JWT

See more Box Examples

Use the encrypted private key in a Box application configuration file to sign a short-lived assertion and exchange it for an access token. Configure and authorize a JWT Server app first. The enterprise subject obtains the service-account token.

See the Box API guide for setup and the complete workflow.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
    //  See Global Unlock Sample.
    //  Guide: Box API Guide.

    success = false;

    CkJsonObject config = new CkJsonObject();
    success = config.LoadFile("qa_data/tokens/box_jwt_config.json");
    if (success != true) {
        Log.i(TAG, config.lastErrorText());
        return;
        }

    CkPrivateKey key = new CkPrivateKey();
    success = key.LoadEncryptedPem(config.stringOf("boxAppSettings.appAuth.privateKey"),config.stringOf("boxAppSettings.appAuth.passphrase"));
    if (success != true) {
        Log.i(TAG, key.lastErrorText());
        return;
        }

    CkJsonObject header = new CkJsonObject();
    header.UpdateString("alg","RS256");
    header.UpdateString("typ","JWT");
    header.UpdateString("kid",config.stringOf("boxAppSettings.appAuth.publicKeyID"));
    CkJwt jwt = new CkJwt();
    CkPrng prng = new CkPrng();
    String nonce = prng.genRandom(32,"hex");
    if (prng.get_LastMethodSuccess() != true) {
        Log.i(TAG, prng.lastErrorText());
        return;
        }

    CkJsonObject claims = new CkJsonObject();
    claims.UpdateString("iss",config.stringOf("boxAppSettings.clientID"));
    claims.UpdateString("sub",config.stringOf("enterpriseID"));
    claims.UpdateString("box_sub_type","enterprise");
    claims.UpdateString("aud","https://api.box.com/oauth2/token");
    claims.UpdateString("jti",nonce);
    claims.UpdateInt("exp",jwt.GenNumericDate(45));
    String assertion = jwt.createJwtPk(header.emit(),claims.emit(),key);
    if (jwt.get_LastMethodSuccess() != true) {
        Log.i(TAG, jwt.lastErrorText());
        return;
        }

    CkHttpCurl curl = new CkHttpCurl();
    curl.SetVar("client_id",config.stringOf("boxAppSettings.clientID"));
    curl.SetVar("client_secret",config.stringOf("boxAppSettings.clientSecret"));
    curl.SetVar("assertion",assertion);
    curl.ClearTargetOutput("*");
    curl.ClearVar("access_token");
    curl.AddTargetOutput("access_token","access_token");
    success = curl.DoYourThing("curl -X POST \"https://api.box.com/oauth2/token\" --data-urlencode \"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer\" --data-urlencode \"client_id={{client_id}}\" --data-urlencode \"client_secret={{client_secret}}\" --data-urlencode \"assertion={{assertion}}\"");
    if ((success != true) or (curl.get_StatusCode() != 200)) {
        Log.i(TAG, "Box request failed. HTTP status: " + String.valueOf(curl.get_StatusCode()));
        Log.i(TAG, "Failure reason: " + String.valueOf(curl.get_FailReason()));
        return;
        }

    if (curl.VarDefined("!") != true) {
        Log.i(TAG, "Expected response fields are missing.");
        return;
        }

    //  Reuse the token in this HttpCurl instance. JWT tokens are renewed by making
    //  a new assertion/token request, not by using a refresh token.
    Log.i(TAG, "JWT access token obtained.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}