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

Outlook Contacts: Refresh a Delegated Access Token

See more Outlook Contact Examples

After interactive authorization, refresh the Graph access token without reopening a browser. Use the same app client ID and authority as the contacts OAuth2 example. Omitting scope retains the original grant. This is delegated access, not application authentication; invalid_grant or an interaction requirement needs fresh interactive authorization.

The example validates the response, retains the previous refresh token when no replacement is returned, and saves a rotated token when present. HTTP or validation failures leave the old cache unchanged. A private backup protects against replacement-write failure; production applications should use protected atomic credential storage and serialize refreshes per account. Tokens are never printed.

Uses qa_data/tokens/outlookContacts.json. Refresh before the acquired time plus expires_in lifetime elapses. Keep the cache associated with its original app and account.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and contact data 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/outlookContacts.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/outlookContacts.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/outlookContacts.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 contacts token cache."

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