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.
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/outlookContacts.json")
If ($bSuccess <> True) Then
ConsoleWrite("Read the private token cache or authorize again." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("refresh_token") <> 1) Or ($oToken.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty refresh_token in the JSON." & @CRLF)
Exit
EndIf
Local $sClientId = "YOUR_APPLICATION_CLIENT_ID"
; Use the same app and authority as the original authorization.
Local $sTokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 30
$oReq = ObjCreate("Chilkat.HttpRequest")
$oReq.HttpVerb = "POST"
$oReq.ContentType = "application/x-www-form-urlencoded"
$oReq.AddParam "client_id",$sClientId
$oReq.AddParam "grant_type","refresh_token"
$oReq.AddParam "refresh_token",$oToken.StringOf("refresh_token")
; Omitting scope retains the original grant instead of requesting additional permissions.
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$bSuccess = $oHttp.HttpReq($sTokenUrl,$oReq,$oResp)
; A false result can still include an HTTP error response.
If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
Exit
EndIf
If ($oResp.StatusCode <> 200) Then
ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
If ($oResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
If ($oResp.StatusCode = 401) Then
ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("access_token") <> 1) Or ($oResult.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("expires_in") <> 2) Or ($oResult.IntOf("expires_in") <= 0)) Then
ConsoleWrite("Missing token lifetime; old cache unchanged." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("refresh_token") = -1) Then
$oResult.UpdateString("refresh_token",$oToken.StringOf("refresh_token"))
Else
If (($oResult.JsonTypeOf("refresh_token") <> 1) Or ($oResult.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty refresh_token in the JSON." & @CRLF)
Exit
EndIf
EndIf
$oObtained = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oObtained.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not timestamp the refreshed token." & @CRLF)
Exit
EndIf
$oResult.UpdateString("obtained_at",$oObtained.GetAsTimestamp(False))
; Keep a valid previous cache for recovery if the replacement write fails.
$bSuccess = $oToken.WriteFile("qa_data/tokens/outlookContacts.json.bak")
If ($bSuccess <> True) Then
ConsoleWrite("Could not back up the old cache; no replacement attempted." & @CRLF)
Exit
EndIf
$bSuccess = $oResult.WriteFile("qa_data/tokens/outlookContacts.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save the new token; recover the previous cache from the private .bak file." & @CRLF)
Exit
EndIf
ConsoleWrite("Refreshed the contacts token cache." & @CRLF)