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

Objective-C
#import <CkoOAuth2.h>
#import <NSString.h>
#import <CkoJsonObject.h>

BOOL success = NO;

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

success = NO;

CkoOAuth2 *oauth2 = [[CkoOAuth2 alloc] init];
oauth2.ListenPort = [NSNumber numberWithInt:3017];
oauth2.AuthorizationEndpoint = @"https://account.box.com/api/oauth2/authorize";
oauth2.TokenEndpoint = @"https://api.box.com/oauth2/token";
oauth2.ClientId = @"BOX_CLIENT_ID";
oauth2.ClientSecret = @"BOX_CLIENT_SECRET";
//  Use Box's documented confidential-client authorization-code flow.
oauth2.CodeChallenge = NO;
NSString *url = [oauth2 StartAuth];
if (oauth2.LastMethodSuccess != YES) {
    NSLog(@"%@",oauth2.LastErrorText);
    return;
}

success = [oauth2 LaunchBrowser: url];
if (success != YES) {
    NSLog(@"%@",oauth2.LastErrorText);
    return;
}

int elapsedMs = 0;
while ((elapsedMs < 120000) && ([oauth2.AuthFlowState intValue] < 3)) {
    [oauth2 SleepMs: [NSNumber numberWithInt: 100]];
    elapsedMs = elapsedMs + 100;
}

if ([oauth2.AuthFlowState intValue] < 3) {
    [oauth2 Cancel];
    NSLog(@"%@",@"Authorization timed out.");
    return;
}

if ([oauth2.AuthFlowState intValue] != 3) {
    NSLog(@"%@%d",@"Authorization was denied or failed. State: ",[oauth2.AuthFlowState intValue]);
    return;
}

//  Retain both tokens in your application's protected token store.
//  The variables below are deliberately not printed.
NSString *accessToken = oauth2.AccessToken;
NSString *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.
CkoJsonObject *tokens = [[CkoJsonObject alloc] init];
success = [tokens Load: oauth2.AccessTokenResponse];
if (success != YES) {
    NSLog(@"%@",tokens.LastErrorText);
    return;
}

success = [tokens WriteFile: @"qa_data/tokens/box_oauth.json"];
if (success != YES) {
    NSLog(@"%@",tokens.LastErrorText);
    return;
}

NSLog(@"%@",@"Authorization complete; token response saved in the protected local token file.");