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

Box: Authorize a User with OAuth 2.0

See more Box Examples

Interactive local-development example using a browser and a loopback callback. Register exactly http://localhost:3017/ in the Box User app. Run this in a trusted environment that can hold the client secret. A deployed web app must handle its registered HTTPS callback on the server.

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

Chilkat Perl Downloads

Perl
use chilkat();

$success = 0;

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

$success = 0;

$oauth2 = chilkat::CkOAuth2->new();
$oauth2->put_ListenPort(3017);
$oauth2->put_AuthorizationEndpoint("https://account.box.com/api/oauth2/authorize");
$oauth2->put_TokenEndpoint("https://api.box.com/oauth2/token");
$oauth2->put_ClientId("BOX_CLIENT_ID");
$oauth2->put_ClientSecret("BOX_CLIENT_SECRET");
#  Use Box's documented confidential-client authorization-code flow.
$oauth2->put_CodeChallenge(0);
$url = $oauth2->startAuth();
if ($oauth2->get_LastMethodSuccess() != 1) {
    print $oauth2->lastErrorText() . "\r\n";
    exit;
}

$success = $oauth2->LaunchBrowser($url);
if ($success != 1) {
    print $oauth2->lastErrorText() . "\r\n";
    exit;
}

$elapsedMs = 0;
while (($elapsedMs < 120000) and ($oauth2->get_AuthFlowState() < 3)) {
    $oauth2->SleepMs(100);
    $elapsedMs = $elapsedMs + 100;
}

if ($oauth2->get_AuthFlowState() < 3) {
    $oauth2->Cancel();
    print "Authorization timed out." . "\r\n";
    exit;
}

if ($oauth2->get_AuthFlowState() != 3) {
    print "Authorization was denied or failed. State: " . $oauth2->get_AuthFlowState() . "\r\n";
    exit;
}

#  Retain both tokens in your application's protected token store.
#  The variables below are deliberately not printed.
$accessToken = $oauth2->accessToken();
$refreshToken = $oauth2->refreshToken();
#  For this local-development example only, save in a directory restricted to this user.
#  Create qa_data/tokens before running; never put this file under a web root.
$tokens = chilkat::CkJsonObject->new();
$success = $tokens->Load($oauth2->accessTokenResponse());
if ($success != 1) {
    print $tokens->lastErrorText() . "\r\n";
    exit;
}

$success = $tokens->WriteFile("qa_data/tokens/box_oauth.json");
if ($success != 1) {
    print $tokens->lastErrorText() . "\r\n";
    exit;
}

print "Authorization complete; token response saved in the protected local token file." . "\r\n";