Box.com OAuth2 with JSON Web Tokens
See more Box Examples
Demonstrates how to obtain an OAuth2 access token using a JSON Web Token. The following explanation is copied from Box Authentication ModelsOAuth2 with JSON Web Tokens enables an application to connect directly to Box and obtain authorization to access files and folders without requiring users to log in. Using OAuth2 with JSON Web Tokens an application can provide Box features without users even being aware that Box exists.
Instead of requiring the user to log in to Box, the application generates JSON Web Token (JWT) verified by an RSA keypair. If this authentication succeeds then the application obtains an access token that grants authorization to operate on Box files and folders. This machine-to-machine authentication replaces the first leg of the three-legged authentication process defined by OAuth2, and enables users of your application to work with Box content without seeing Box login requests.
OAuth2 with JSON Web Tokens is designed to be used with Box Platform. You can use OAuth2 with JWT with both Service Accounts and App Users.
Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoJsonRsaKey
String sPassphrase
String sPrivateKeyPem
Variant vRsaKey
Handle hoRsaKey
Handle hoJwt
Handle hoJose
Handle hoClaims
Handle hoPrng
Handle hoRest
Boolean iBAutoReconnect
String sJsonResponse
Handle hoJResponse
String sAccessToken
String sTemp1
Integer iTemp1
Boolean bTemp1
Move False To iSuccess
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// When you created an RSA key pair using the Box web user interface,
// you downloaded a json file named something like "7152782_kkdxptq2_config.json"
// This contains the following:
// {
// "boxAppSettings": {
// "clientID": "0kraci84o0jfr7yuw596tf394iigzbe7",
// "clientSecret": "xxxxxxxxxxxxxxxxxxxxxxxxx",
// "appAuth": {
// "publicKeyID": "kkdxptq2",
// "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDj ... nceU=\n-----END ENCRYPTED PRIVATE KEY-----\n",
// "passphrase": "xxxxxxxxxxxxxxxxxxxxxxxx"
// }
// },
// "enterpriseID": "7152782"
// }
//
// Load it into a Chilkat JSON object to allow access to the content.
Get Create (RefClass(cComChilkatJsonObject)) To hoJsonRsaKey
If (Not(IsComObjectCreated(hoJsonRsaKey))) Begin
Send CreateComObject of hoJsonRsaKey
End
Get ComLoadFile Of hoJsonRsaKey "qa_data/tokens/7152782_kkdxptq2_config.json" To iSuccess
// Load the private key into a Chilkat private key object.
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.appAuth.passphrase" To sPassphrase
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.appAuth.privateKey" To sPrivateKeyPem
Get Create (RefClass(cComChilkatPrivateKey)) To hoRsaKey
If (Not(IsComObjectCreated(hoRsaKey))) Begin
Send CreateComObject of hoRsaKey
End
Get ComLoadEncryptedPem Of hoRsaKey sPrivateKeyPem sPassphrase To iSuccess
If (iSuccess <> True) Begin
Get ComLastErrorText Of hoRsaKey To sTemp1
Showln sTemp1
Procedure_Return
End
// The JSON Web Token will be created using the JWT class
Get Create (RefClass(cComChilkatJwt)) To hoJwt
If (Not(IsComObjectCreated(hoJwt))) Begin
Send CreateComObject of hoJwt
End
// Construct the JOSE header...
Get Create (RefClass(cComChilkatJsonObject)) To hoJose
If (Not(IsComObjectCreated(hoJose))) Begin
Send CreateComObject of hoJose
End
// Chilkat supports the following algorithms: "RS256", "RS384", and "RS512". (Chilkat also supports other algorithms that Box does not yet support.)
Get ComUpdateString Of hoJose "alg" "RS256" To iSuccess
Get ComUpdateString Of hoJose "typ" "JWT" To iSuccess
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.appAuth.publicKeyID" To sTemp1
Get ComUpdateString Of hoJose "kid" sTemp1 To iSuccess
// Now let's build the JWT claims. Most of this is just boilerplate (i.e. the same every time..)
// The JWT claims contain these required and optional elements:
// iss (required, String) The Client ID of the service that created the JWT assertion.
// sub (required, String) enterprise_id for a token specific to an enterprise when creating and managing app users, or the app user_id for a token specific to an individual app user.
// box_sub_type (required, String) "enterprise" or "user" depending on the type of token being requested in the sub claim.
// aud (required, String) Always "https://api.box.com/oauth2/token" for OAuth2 token requests
// jti (required, String) A universally unique identifier specified by the client for this JWT. This is a unique string that is at least 16 characters and at most 128 characters.
// exp (required, NumericDate) The unix time as to when this JWT will expire. This can be set to a maximum value of 60 seconds beyond the issue time. Note: It is recommended to set this value to less than the maximum allowed 60 seconds.
// iat (optional, NumericDate) Issued at time. The token cannot be used before this time.
// nbf (optional, NumericDate) Not before. Specifies when the token will start being valid.
//
Get Create (RefClass(cComChilkatJsonObject)) To hoClaims
If (Not(IsComObjectCreated(hoClaims))) Begin
Send CreateComObject of hoClaims
End
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.clientID" To sTemp1
Get ComUpdateString Of hoClaims "iss" sTemp1 To iSuccess
Get ComStringOf Of hoJsonRsaKey "enterpriseID" To sTemp1
Get ComUpdateString Of hoClaims "sub" sTemp1 To iSuccess
Get ComUpdateString Of hoClaims "box_sub_type" "enterprise" To iSuccess
Get ComUpdateString Of hoClaims "aud" "https://api.box.com/oauth2/token" To iSuccess
// Generate 32 random bytes (base64 encoded) for the "jti"
Get Create (RefClass(cComChilkatPrng)) To hoPrng
If (Not(IsComObjectCreated(hoPrng))) Begin
Send CreateComObject of hoPrng
End
Get ComGenRandom Of hoPrng 32 "base64" To sTemp1
Get ComUpdateString Of hoClaims "jti" sTemp1 To iSuccess
// Set the expiration time to 60 seconds after the current time.
Get ComGenNumericDate Of hoJwt 60 To iTemp1
Get ComUpdateInt Of hoClaims "exp" iTemp1 To iSuccess
// We're going to do the following POST to get a JSON response that contains our OAuth2 access token:
// POST /oauth2/token
// Content-Type: application/x-www-form-urlencoded
// grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&
// assertion=<JWT>&
// client_id=<client_id>&
// client_secret=<client_secret>
// First, make the initial connection.
// A single REST object, once connected, can be used for many Box REST API calls.
// The auto-reconnect indicates that if the already-established HTTPS connection is closed,
// then it will be automatically re-established as needed.
Get Create (RefClass(cComChilkatRest)) To hoRest
If (Not(IsComObjectCreated(hoRest))) Begin
Send CreateComObject of hoRest
End
Move True To iBAutoReconnect
Get ComConnect Of hoRest "api.box.com" 443 True iBAutoReconnect To iSuccess
If (iSuccess <> True) Begin
Get ComLastErrorText Of hoRest To sTemp1
Showln sTemp1
Procedure_Return
End
// Add the query params.
// Calling ClearAllParts is wise if previous requests were sent prior to this one on the same REST object..
Get ComClearAllParts Of hoRest To iSuccess
Get ComAddQueryParam Of hoRest "grant_type" "urn:ietf:params:oauth:grant-type:jwt-bearer" To iSuccess
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.clientID" To sTemp1
Get ComAddQueryParam Of hoRest "client_id" sTemp1 To iSuccess
Get ComStringOf Of hoJsonRsaKey "boxAppSettings.clientSecret" To sTemp1
Get ComAddQueryParam Of hoRest "client_secret" sTemp1 To iSuccess
Get ComCreateJwtPk Of hoJwt (ComEmit(hoJose)) (ComEmit(hoClaims)) Get pvComObject of hoRsaKey to vRsaKey
vRsaKey To sTemp1
Get ComAddQueryParam Of hoRest "assertion" sTemp1 To iSuccess
Get ComFullRequestFormUrlEncoded Of hoRest "POST" "/oauth2/token" To sJsonResponse
Get ComLastMethodSuccess Of hoRest To bTemp1
If (bTemp1 <> True) Begin
Get ComLastErrorText Of hoRest To sTemp1
Showln sTemp1
Procedure_Return
End
// If successful, we'll get a response status code equal to 200,
// and a JSON response that looks like this:
// {
// "access_token": "mNr1FrCvOeWiGnwLL0OcTL0Lux5jbyBa",
// "expires_in": 4169,
// "restricted_to": [],
// "token_type": "bearer"
// }
//
Get Create (RefClass(cComChilkatJsonObject)) To hoJResponse
If (Not(IsComObjectCreated(hoJResponse))) Begin
Send CreateComObject of hoJResponse
End
Set ComEmitCompact Of hoJResponse To False
Get ComLoad Of hoJResponse sJsonResponse To iSuccess
Get ComResponseStatusCode Of hoRest To iTemp1
If (iTemp1 <> 200) Begin
Get ComEmit Of hoJResponse To sTemp1
Showln sTemp1
Showln "Failed."
Procedure_Return
End
Get ComEmit Of hoJResponse To sTemp1
Showln sTemp1
// Get the access token:
Get ComStringOf Of hoJResponse "access_token" To sAccessToken
Showln "Access token, valid for 60 minutes: " sAccessToken
End_Procedure