Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.6.0+

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
set success 0
set token [new_CkJsonObject]

CkJsonObject_put_Strict $token 1
set success [CkJsonObject_LoadFile $token "qa_data/tokens/oneDrive.json"]
if {$success != 1} then {
    puts "Read the private token cache or authorize again."
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "refresh_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "refresh_token" "" 1] == 1]} then {
    puts "Expected a nonempty refresh_token in the JSON."
    delete_CkJsonObject $token
    exit
}

set clientId "YOUR_APPLICATION_CLIENT_ID"
#  Use the same app and authority as the original authorization.
set tokenUrl "https://login.microsoftonline.com/common/oauth2/v2.0/token"
set http [new_CkHttp]

CkHttp_put_RequireSslCertVerify $http 1
CkHttp_put_FollowRedirects $http 0
CkHttp_put_ConnectTimeout $http 20
CkHttp_put_ReadTimeout $http 30
set req [new_CkHttpRequest]

CkHttpRequest_put_HttpVerb $req "POST"
CkHttpRequest_put_ContentType $req "application/x-www-form-urlencoded"
CkHttpRequest_AddParam $req "client_id" $clientId
CkHttpRequest_AddParam $req "grant_type" "refresh_token"
CkHttpRequest_AddParam $req "refresh_token" [CkJsonObject_stringOf $token "refresh_token"]
#  Omitting scope retains the original grant instead of requesting additional permissions.
set resp [new_CkHttpResponse]

set result [new_CkJsonObject]

CkJsonObject_put_Strict $result 1
set success [CkHttp_HttpReq $http $tokenUrl $req $resp]
#  A false result can still include an HTTP error response.
if {expr [$success != 1]  &&  [[CkHttpResponse_get_StatusCode $resp] == 0]} then {
    puts "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    exit
}

if {[CkHttpResponse_get_StatusCode $resp] != 200} then {
    puts "Unexpected HTTP status: [CkHttpResponse_get_StatusCode $resp]"
    puts "Request ID: [CkHttpResponse_getHeaderField $resp request-id]"
    if {[CkHttpResponse_get_StatusCode $resp] == 429} then {
        puts "Retry-After: [CkHttpResponse_getHeaderField $resp Retry-After]"
    }

    if {[CkHttpResponse_get_StatusCode $resp] == 401} then {
        puts "Refresh the Graph access token or authorize again."
    }

    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    exit
}

set success [CkJsonObject_Load $result [CkHttpResponse_bodyStr $resp]]
if {$success != 1} then {
    puts "Expected a well-formed JSON response."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $result "access_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $result "access_token" "" 1] == 1]} then {
    puts "Expected a nonempty access_token in the JSON."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $result "expires_in"] != 2]  ||  [[CkJsonObject_IntOf $result "expires_in"] <= 0]} then {
    puts "Missing token lifetime; old cache unchanged."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    exit
}

if {[CkJsonObject_JsonTypeOf $result "refresh_token"] == -1} then {
    CkJsonObject_UpdateString $result "refresh_token" [CkJsonObject_stringOf $token "refresh_token"]
} else {
    if {expr [[CkJsonObject_JsonTypeOf $result "refresh_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $result "refresh_token" "" 1] == 1]} then {
        puts "Expected a nonempty refresh_token in the JSON."
        delete_CkJsonObject $token
        delete_CkHttp $http
        delete_CkHttpRequest $req
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        exit
    }

}

set obtained [new_CkDateTime]

set success [CkDateTime_SetFromCurrentSystemTime $obtained]
if {$success != 1} then {
    puts "Could not timestamp the refreshed token."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkDateTime $obtained
    exit
}

CkJsonObject_UpdateString $result "obtained_at" [CkDateTime_getAsTimestamp $obtained 0]
#  Keep a valid previous cache for recovery if the replacement write fails.
set success [CkJsonObject_WriteFile $token "qa_data/tokens/oneDrive.json.bak"]
if {$success != 1} then {
    puts "Could not back up the old cache; no replacement attempted."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkDateTime $obtained
    exit
}

set success [CkJsonObject_WriteFile $result "qa_data/tokens/oneDrive.json"]
if {$success != 1} then {
    puts "Could not save the new token; recover the previous cache from the private .bak file."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpRequest $req
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkDateTime $obtained
    exit
}

puts "Refreshed the OneDrive token cache."

delete_CkJsonObject $token
delete_CkHttp $http
delete_CkHttpRequest $req
delete_CkHttpResponse $resp
delete_CkJsonObject $result
delete_CkDateTime $obtained