Sample code for 30+ languages & platforms
Unicode C++ 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 Unicode C++ Downloads

Unicode C++
#include <CkOAuth2W.h>
#include <CkJsonObjectW.h>

void ChilkatSample(void)
    {
    bool 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;

    CkOAuth2W oauth2;
    oauth2.put_ListenPort(3017);
    oauth2.put_AuthorizationEndpoint(L"https://account.box.com/api/oauth2/authorize");
    oauth2.put_TokenEndpoint(L"https://api.box.com/oauth2/token");
    oauth2.put_ClientId(L"BOX_CLIENT_ID");
    oauth2.put_ClientSecret(L"BOX_CLIENT_SECRET");
    //  Use Box's documented confidential-client authorization-code flow.
    oauth2.put_CodeChallenge(false);
    const wchar_t *url = oauth2.startAuth();
    if (oauth2.get_LastMethodSuccess() != true) {
        wprintf(L"%s\n",oauth2.lastErrorText());
        return;
    }

    success = oauth2.LaunchBrowser(url);
    if (success != true) {
        wprintf(L"%s\n",oauth2.lastErrorText());
        return;
    }

    int elapsedMs = 0;
    while ((elapsedMs < 120000) && (oauth2.get_AuthFlowState() < 3)) {
        oauth2.SleepMs(100);
        elapsedMs = elapsedMs + 100;
    }

    if (oauth2.get_AuthFlowState() < 3) {
        oauth2.Cancel();
        wprintf(L"Authorization timed out.\n");
        return;
    }

    if (oauth2.get_AuthFlowState() != 3) {
        wprintf(L"Authorization was denied or failed. State: %d\n",oauth2.get_AuthFlowState());
        return;
    }

    //  Retain both tokens in your application's protected token store.
    //  The variables below are deliberately not printed.
    const wchar_t *accessToken = oauth2.accessToken();
    const wchar_t *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.
    CkJsonObjectW tokens;
    success = tokens.Load(oauth2.accessTokenResponse());
    if (success != true) {
        wprintf(L"%s\n",tokens.lastErrorText());
        return;
    }

    success = tokens.WriteFile(L"qa_data/tokens/box_oauth.json");
    if (success != true) {
        wprintf(L"%s\n",tokens.lastErrorText());
        return;
    }

    wprintf(L"Authorization complete; token response saved in the protected local token file.\n");
    }