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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    var success: bool = false;

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

    success = false;

    const oauth2 = try chilkat.OAuth2.init();
    defer oauth2.deinit();
    oauth2.setListenPort(3017);
    oauth2.setAuthorizationEndpoint("https://account.box.com/api/oauth2/authorize");
    oauth2.setTokenEndpoint("https://api.box.com/oauth2/token");
    oauth2.setClientId("BOX_CLIENT_ID");
    oauth2.setClientSecret("BOX_CLIENT_SECRET");
    // Use Box's documented confidential-client authorization-code flow.
    oauth2.setCodeChallenge(false);
    const url = oauth2.startAuth(alloc) catch {
        std.debug.print("{s}\n", .{try oauth2.getLastErrorText(alloc)});
        return;
    };

    oauth2.launchBrowser(url) catch {
        std.debug.print("{s}\n", .{try oauth2.getLastErrorText(alloc)});
        return;
    };

    var elapsed_ms: i32 = 0;
    while ((elapsed_ms < 120000) and (oauth2.getAuthFlowState() < 3)) {
        oauth2.sleepMs(100);
        elapsed_ms = elapsed_ms + 100;
    }

    if (oauth2.getAuthFlowState() < 3) {
        oauth2.cancel() catch {};
        std.debug.print("Authorization timed out.\n", .{});
        return;
    }

    if (oauth2.getAuthFlowState() != 3) {
        std.debug.print("Authorization was denied or failed. State: {d}\n", .{oauth2.getAuthFlowState()});
        return;
    }

    // Retain both tokens in your application's protected token store.
    // The variables below are deliberately not printed.
    _ = try oauth2.getAccessToken(alloc);
    _ = try oauth2.getRefreshToken(alloc);
    // 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.
    const tokens = try chilkat.JsonObject.init();
    defer tokens.deinit();
    tokens.load(try oauth2.getAccessTokenResponse(alloc)) catch {
        std.debug.print("{s}\n", .{try tokens.getLastErrorText(alloc)});
        return;
    };

    tokens.writeFile("qa_data/tokens/box_oauth.json") catch {
        std.debug.print("{s}\n", .{try tokens.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Authorization complete; token response saved in the protected local token file.\n", .{});
}