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 PowerShell Downloads
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"
$success = $false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = $false
$token = New-Object Chilkat.JsonObject
$token.Strict = $true
$success = $token.LoadFile("qa_data/tokens/outlookContacts.json")
if ($success -ne $true) {
$("Read the private token cache or authorize again.")
exit
}
if (($token.JsonTypeOf("refresh_token") -ne 1) -or ($token.StringOfEquals("refresh_token","",$true) -eq $true)) {
$("Expected a nonempty refresh_token in the JSON.")
exit
}
$clientId = "YOUR_APPLICATION_CLIENT_ID"
# Use the same app and authority as the original authorization.
$tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
$http.FollowRedirects = $false
$http.ConnectTimeout = 20
$http.ReadTimeout = 30
$req = New-Object Chilkat.HttpRequest
$req.HttpVerb = "POST"
$req.ContentType = "application/x-www-form-urlencoded"
$req.AddParam("client_id",$clientId)
$req.AddParam("grant_type","refresh_token")
$req.AddParam("refresh_token",$token.StringOf("refresh_token"))
# Omitting scope retains the original grant instead of requesting additional permissions.
$resp = New-Object Chilkat.HttpResponse
$result = New-Object Chilkat.JsonObject
$result.Strict = $true
$success = $http.HttpReq($tokenUrl,$req,$resp)
# A false result can still include an HTTP error response.
if (($success -ne $true) -and ($resp.StatusCode -eq 0)) {
$("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
exit
}
if ($resp.StatusCode -ne 200) {
$("Unexpected HTTP status: " + $resp.StatusCode)
$("Request ID: " + $resp.GetHeaderField("request-id"))
if ($resp.StatusCode -eq 429) {
$("Retry-After: " + $resp.GetHeaderField("Retry-After"))
}
if ($resp.StatusCode -eq 401) {
$("Refresh the Graph access token or authorize again.")
}
exit
}
$success = $result.Load($resp.BodyStr)
if ($success -ne $true) {
$("Expected a well-formed JSON response.")
exit
}
if (($result.JsonTypeOf("access_token") -ne 1) -or ($result.StringOfEquals("access_token","",$true) -eq $true)) {
$("Expected a nonempty access_token in the JSON.")
exit
}
if (($result.JsonTypeOf("expires_in") -ne 2) -or ($result.IntOf("expires_in") -le 0)) {
$("Missing token lifetime; old cache unchanged.")
exit
}
if ($result.JsonTypeOf("refresh_token") -eq -1) {
$result.UpdateString("refresh_token",$token.StringOf("refresh_token"))
}
else {
if (($result.JsonTypeOf("refresh_token") -ne 1) -or ($result.StringOfEquals("refresh_token","",$true) -eq $true)) {
$("Expected a nonempty refresh_token in the JSON.")
exit
}
}
$obtained = New-Object Chilkat.CkDateTime
$success = $obtained.SetFromCurrentSystemTime()
if ($success -ne $true) {
$("Could not timestamp the refreshed token.")
exit
}
$result.UpdateString("obtained_at",$obtained.GetAsTimestamp($false))
# Keep a valid previous cache for recovery if the replacement write fails.
$success = $token.WriteFile("qa_data/tokens/outlookContacts.json.bak")
if ($success -ne $true) {
$("Could not back up the old cache; no replacement attempted.")
exit
}
$success = $result.WriteFile("qa_data/tokens/outlookContacts.json")
if ($success -ne $true) {
$("Could not save the new token; recover the previous cache from the private .bak file.")
exit
}
$("Refreshed the contacts token cache.")