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

Box: Get a Service Account Token with Client Credentials

See more Box Examples

Obtain a Box service-account token using the client credentials grant. Configure and authorize a Server app first. Load credentials from protected application configuration; do not ship a client secret in a public client.

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

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

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

success = False

Dim curl As ChilkatHttpCurl
curl.Initialize("curl")
curl.SetVar("client_id", "BOX_CLIENT_ID")
curl.SetVar("client_secret", "BOX_CLIENT_SECRET")
curl.SetVar("enterprise_id", "BOX_ENTERPRISE_ID")
'  enterprise identifies the app's service account. This is not an admin-user token.
curl.ClearTargetOutput("*")
curl.ClearVar("access_token")
curl.AddTargetOutput("access_token", "access_token")
success = curl.DoYourThing("curl -X POST " & Chr(34) & "https://api.box.com/oauth2/token" & Chr(34) & " --data-urlencode " & Chr(34) & "grant_type=client_credentials" & Chr(34) & " --data-urlencode " & Chr(34) & "client_id={{client_id}}" & Chr(34) & " --data-urlencode " & Chr(34) & "client_secret={{client_secret}}" & Chr(34) & " --data-urlencode " & Chr(34) & "box_subject_type=enterprise" & Chr(34) & " --data-urlencode " & Chr(34) & "box_subject_id={{enterprise_id}}" & Chr(34))
If (success <> True) Or (curl.StatusCode <> 200) Then
    Log("Box request failed. HTTP status: " & curl.StatusCode)
    Log("Failure reason: " & curl.FailReason)
    Return
End If

If curl.VarDefined("!") <> True Then
    Log("Expected response fields are missing.")
    Return
End If

'  Keep this token in protected application memory; reacquire it when it expires.
'  Do not print tokens or the complete token response.
Log("Service-account access token obtained.")
curl.ClearTargetOutput("*")
Dim authorizedCommand1 As ChilkatStringBuilder
authorizedCommand1.Initialize
authorizedCommand1.SetString("curl -X GET " & Chr(34) & "https://api.box.com/2.0/users/me?fields=id,name,login" & Chr(34) & " -H " & Chr(34) & "Authorization: Bearer {{access_token}}" & Chr(34))
Dim headerReplacement1 As Int = authorizedCommand1.Replace("{{access_token}}", curl.GetVar("access_token"))
success = curl.DoYourThing(authorizedCommand1.GetAsString)
If (success <> True) Or (curl.StatusCode <> 200) Then
    Log("Box request failed. HTTP status: " & curl.StatusCode)
    Log("Failure reason: " & curl.FailReason)
    Log(curl.ResponseBodyStr)
    Return
End If

Log(curl.ResponseBodyStr)