Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

OneDrive: Obtain and Refresh a SharePoint Transfer Token

See more OneDrive Examples

Obtain and refresh a delegated SharePoint Online access token for the OneDrive download, upload-session, version-download, and copy-monitor examples. This is for Microsoft 365 work/school accounts, not personal OneDrive. It saves qa_data/tokens/oneDrive-sharepoint.json with the exact host and access_token those transfer examples read, plus a refresh token, lifetime, acquisition time, and cache context. The Graph cache oneDrive.json remains separate.

Register a public application in Microsoft Entra, select the intended organizational account type, and add http://localhost:3017/ as a Mobile and desktop applications redirect URI. Set tenantId to the Directory (tenant) GUID and clientId to the Application (client) ID. Add the appropriate SharePoint delegated permissions in API permissions: use MyFiles.Read for reading the user's files or MyFiles.Write for writing them; use AllSites.Read or AllSites.Write where broader SharePoint site access is needed. Select only the permissions required and obtain consent as tenant policy requires. The user's actual access still applies. Graph permissions alone do not establish this SharePoint grant.

Set sharepointHost from trusted configuration: typically tenant.sharepoint.com for SharePoint libraries or tenant-my.sharepoint.com for the user's business OneDrive. Use the exact host expected by the transfer examples, without a scheme, path, port, or wildcard. This global-cloud example requests https://{host}/.default, which uses configured, consented SharePoint permissions, plus offline_access during authorization. Do not combine .default with dynamic API permission scopes. If newly configured permissions are not already consented, arrange renewed consent; refreshing does not grant them. How .default consent works.

Run action="authorize" for initial PKCE browser sign-in, choosing the same intended user as the Graph workflow. This explicitly replaces an existing cache after validation and backup. Change to action="refresh" for unattended renewal before obtained_at plus expires_in, allowing a safety margin. Refresh sends an explicit SharePoint resource scope and never opens a browser automatically. It saves a rotated refresh token, or retains the previous one when omitted. Revocation, Conditional Access, invalid_grant, or interaction requirements can require a new sign-in.

The local accountKey is an application-defined cache key, not a verified identity claim. The refresh branch requires matching host, tenant, client, account key, and resource scope before sending credentials. Use separate protected caches for different contexts and update the transfer cache path accordingly. Existing hand-written caches without the refresh/context fields need authorize. Do not decode an access token and assume its internal format or audience claim is a stable client contract.

Only validated responses replace the cache. A checked private backup supports recovery; production applications should serialize refreshes and commit credentials atomically in protected storage. Neither token is printed. A loopback listener is required only for initial sign-in; no hosted web server is needed. This is not certificate-based application access, which obtains new tokens through client credentials and has no refresh token.

OneDrive transfer authentication guide. Microsoft's SharePoint delegated permission overview.

Permission: Configured SharePoint delegated permissions and offline_access.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Objective-C Downloads

Objective-C
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoFileAccess.h>
#import <CkoOAuth2.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
//  Run authorize once; change to refresh for subsequent unattended renewals.
NSString *action = @"authorize";
NSString *tenantId = @"YOUR_TENANT_ID";
NSString *clientId = @"YOUR_APPLICATION_CLIENT_ID";
//  A trusted bare hostname, e.g. tenant.sharepoint.com or tenant-my.sharepoint.com.
//  Configure the exact host used by the intended transfer; do not copy an untrusted URL here.
NSString *sharepointHost = @"YOUR_TENANT.sharepoint.com";
//  An application-defined key for this user/account, not an access token or password.
NSString *accountKey = @"YOUR_LOCAL_ACCOUNT_KEY";
NSString *cachePath = @"qa_data/tokens/oneDrive-sharepoint.json";
NSString *backupPath = @"qa_data/tokens/oneDrive-sharepoint.json.bak";
if ((action != @"authorize") && (action != @"refresh")) {
    NSLog(@"%@",@"Choose authorize or refresh.");
    return;
}

CkoStringBuilder *host = [[CkoStringBuilder alloc] init];
[host Append: sharepointHost];
CkoJsonObject *match = [[CkoJsonObject alloc] init];
int matched = [[host RegexMatch: @"(?i)\\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.sharepoint\\.com\\z" json: match timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (matched != 1) {
    NSLog(@"%@",@"Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.");
    return;
}

//  Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
CkoStringBuilder *tenant = [[CkoStringBuilder alloc] init];
[tenant Append: tenantId];
matched = [[tenant RegexMatch: @"(?i)\\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\z" json: match timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (matched != 1) {
    NSLog(@"%@",@"Set the organization tenant GUID before running.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:30];
CkoStringBuilder *tokenEndpoint = [[CkoStringBuilder alloc] init];
[tokenEndpoint Append: @"https://login.microsoftonline.com/"];
[tokenEndpoint Append: [http UrlEncode: tenantId]];
[tokenEndpoint Append: @"/oauth2/v2.0/token"];
CkoStringBuilder *authorizeEndpoint = [[CkoStringBuilder alloc] init];
[authorizeEndpoint Append: @"https://login.microsoftonline.com/"];
[authorizeEndpoint Append: [http UrlEncode: tenantId]];
[authorizeEndpoint Append: @"/oauth2/v2.0/authorize"];
CkoStringBuilder *scopeBuilder = [[CkoStringBuilder alloc] init];
[scopeBuilder Append: @"https://"];
[scopeBuilder Append: sharepointHost];
[scopeBuilder Append: @"/.default"];
NSString *resourceScope = [scopeBuilder GetAsString];
CkoFileAccess *fac = [[CkoFileAccess alloc] init];
BOOL hadCache = [fac FileExists: cachePath];
CkoJsonObject *previous = [[CkoJsonObject alloc] init];
previous.Strict = YES;
if (hadCache == YES) {
    success = [previous LoadFile: cachePath];
    if (success != YES) {
        NSLog(@"%@",@"Invalid existing cache; recover its private backup before continuing.");
        return;
    }

}

CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
if (action == @"authorize") {
    //  Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
    CkoOAuth2 *oauth = [[CkoOAuth2 alloc] init];
    oauth.AuthorizationEndpoint = [authorizeEndpoint GetAsString];
    oauth.TokenEndpoint = [tokenEndpoint GetAsString];
    oauth.ClientId = clientId;
    oauth.LocalHost = @"localhost";
    oauth.ListenPort = [NSNumber numberWithInt:3017];
    oauth.CodeChallenge = YES;
    oauth.CodeChallengeMethod = @"S256";
    //  No client secret in a public desktop application.
    CkoStringBuilder *scopes = [[CkoStringBuilder alloc] init];
    [scopes Append: @"offline_access "];
    [scopes Append: resourceScope];
    oauth.Scope = [scopes GetAsString];
    success = [oauth AddAuthQueryParam: @"prompt" value: @"select_account"];
    if (success != YES) {
        NSLog(@"%@",@"Could not configure the authorization request.");
        return;
    }

    NSString *authUrl = [oauth StartAuth];
    if (oauth.LastMethodSuccess != YES) {
        NSLog(@"%@",@"Could not start the local authorization listener.");
        return;
    }

    success = [oauth LaunchBrowser: authUrl];
    if (success != YES) {
        [oauth Cancel];
        NSLog(@"%@",@"Could not open the system browser.");
        return;
    }

    int waited = 0;
    while ((([oauth.AuthFlowState intValue] < 3) && (waited < 180000))) {
        [oauth SleepMs: [NSNumber numberWithInt: 200]];
        waited = waited + 200;
    }

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

    if ([oauth.AuthFlowState intValue] != 3) {
        NSLog(@"%@%d",@"Authorization did not complete. Flow state: ",[oauth.AuthFlowState intValue]);
        return;
    }

    success = [result Load: oauth.AccessTokenResponse];
    if (success != YES) {
        NSLog(@"%@",@"Invalid token response; existing cache unchanged.");
        return;
    }

    if (([[result JsonTypeOf: @"refresh_token"] intValue] != 1) || ([result StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
        NSLog(@"%@",@"Expected a nonempty refresh_token in the JSON.");
        return;
    }

}
else {
    if (hadCache != YES) {
        NSLog(@"%@",@"No SharePoint token cache. Run authorize first.");
        return;
    }

    if ([previous StringOfEquals: @"host" value: sharepointHost caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.");
        return;
    }

    if ([previous StringOfEquals: @"tenant_id" value: tenantId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.");
        return;
    }

    if ([previous StringOfEquals: @"client_id" value: clientId caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.");
        return;
    }

    if ([previous StringOfEquals: @"account_key" value: accountKey caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.");
        return;
    }

    if ([previous StringOfEquals: @"resource_scope" value: resourceScope caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.");
        return;
    }

    if (([[previous JsonTypeOf: @"refresh_token"] intValue] != 1) || ([previous StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
        NSLog(@"%@",@"Expected a nonempty refresh_token in the JSON.");
        return;
    }

    CkoHttpRequest *req = [[CkoHttpRequest alloc] init];
    req.HttpVerb = @"POST";
    req.ContentType = @"application/x-www-form-urlencoded";
    [req AddParam: @"client_id" value: clientId];
    [req AddParam: @"grant_type" value: @"refresh_token"];
    [req AddParam: @"refresh_token" value: [previous StringOf: @"refresh_token"]];
    //  Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
    [req AddParam: @"scope" value: resourceScope];
    CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
    success = [http HttpReq: [tokenEndpoint GetAsString] request: req response: resp];
    if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
        NSLog(@"%@",@"No token response received; existing cache unchanged.");
        return;
    }

    if ([resp.StatusCode intValue] != 200) {
        NSLog(@"%@%d",@"Token renewal failed. HTTP status: ",[resp.StatusCode intValue]);
        if ([resp.StatusCode intValue] == 429) {
            NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
        }

        NSLog(@"%@",@"Check consent and token validity. If interaction is required, run authorize deliberately.");
        return;
    }

    if (success != YES) {
        NSLog(@"%@",@"Token response did not complete; existing cache unchanged.");
        return;
    }

    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Invalid refresh response; existing cache unchanged.");
        return;
    }

    if ([[result JsonTypeOf: @"refresh_token"] intValue] == -1) {
        [result UpdateString: @"refresh_token" value: [previous StringOf: @"refresh_token"]];
    }
    else {
        if (([[result JsonTypeOf: @"refresh_token"] intValue] != 1) || ([result StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
            NSLog(@"%@",@"Expected a nonempty refresh_token in the JSON.");
            return;
        }

    }

}

if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || ([result StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
    return;
}

if (([[result JsonTypeOf: @"expires_in"] intValue] != 2) || ([[result IntOf: @"expires_in"] intValue] <= 0)) {
    NSLog(@"%@",@"Expected a positive access-token lifetime; existing cache unchanged.");
    return;
}

if ([result StringOfEquals: @"token_type" value: @"Bearer" caseSensitive: NO] != YES) {
    NSLog(@"%@",@"Expected a bearer access token; existing cache unchanged.");
    return;
}

CkoDateTime *obtained = [[CkoDateTime alloc] init];
success = [obtained SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not timestamp the access token.");
    return;
}

[result UpdateString: @"obtained_at" value: [obtained GetAsTimestamp: NO]];
//  The transfer examples read host and access_token; these extra fields bind future refreshes.
[result UpdateString: @"host" value: sharepointHost];
[result UpdateString: @"tenant_id" value: tenantId];
[result UpdateString: @"client_id" value: clientId];
[result UpdateString: @"account_key" value: accountKey];
[result UpdateString: @"resource_scope" value: resourceScope];
success = [fac DirEnsureExists: @"qa_data/tokens"];
if (success != YES) {
    NSLog(@"%@",@"Could not create the private cache directory.");
    return;
}

if (hadCache == YES) {
    success = [previous WriteFile: backupPath];
    if (success != YES) {
        NSLog(@"%@",@"Could not back up the previous cache; no replacement attempted.");
        return;
    }

}

success = [result WriteFile: cachePath];
if (success != YES) {
    NSLog(@"%@",@"Could not save the new cache; recover the private backup if an older cache existed.");
    return;
}

//  Never print the tokens, token response, or authorization URL.
NSLog(@"%@",@"SharePoint token cache saved. The OneDrive transfer examples can now load it.");