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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/outlookContacts.json")
if not success then
print("Read the private token cache or authorize again.")
return
end
if (token:json_type_of("refresh_token") ~= 1) or (token:string_of_equals("refresh_token", "", true)) then
print("Expected a nonempty refresh_token in the JSON.")
return
end
local clientId = "YOUR_APPLICATION_CLIENT_ID"
-- Use the same app and authority as the original authorization.
local tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 30
local req = chilkat.HttpRequest.new()
req.http_verb = "POST"
req.content_type = "application/x-www-form-urlencoded"
req:add_param("client_id", clientId)
req:add_param("grant_type", "refresh_token")
req:add_param("refresh_token", token:string_of("refresh_token"))
-- Omitting scope retains the original grant instead of requesting additional permissions.
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
success = http:http_req(tokenUrl, req, resp)
-- A false result can still include an HTTP error response.
if (not success) and (resp.status_code == 0) then
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
end
if resp.status_code ~= 200 then
print("Unexpected HTTP status: " .. resp.status_code)
print("Request ID: " .. resp:get_header_field("request-id"))
if resp.status_code == 429 then
print("Retry-After: " .. resp:get_header_field("Retry-After"))
end
if resp.status_code == 401 then
print("Refresh the Graph access token or authorize again.")
end
return
end
success = result:load(resp.body_str)
if not success then
print("Expected a well-formed JSON response.")
return
end
if (result:json_type_of("access_token") ~= 1) or (result:string_of_equals("access_token", "", true)) then
print("Expected a nonempty access_token in the JSON.")
return
end
if (result:json_type_of("expires_in") ~= 2) or (result:int_of("expires_in") <= 0) then
print("Missing token lifetime; old cache unchanged.")
return
end
if result:json_type_of("refresh_token") == (-1) then
result:update_string("refresh_token", token:string_of("refresh_token"))
elseif (result:json_type_of("refresh_token") ~= 1) or (result:string_of_equals("refresh_token", "", true)) then
print("Expected a nonempty refresh_token in the JSON.")
return
end
local obtained = chilkat.DateTime.new()
success = obtained:set_from_current_system_time()
if not success then
print("Could not timestamp the refreshed token.")
return
end
result:update_string("obtained_at", obtained:get_as_timestamp(false))
-- Keep a valid previous cache for recovery if the replacement write fails.
success = token:write_file("qa_data/tokens/outlookContacts.json.bak")
if not success then
print("Could not back up the old cache; no replacement attempted.")
return
end
success = result:write_file("qa_data/tokens/outlookContacts.json")
if not success then
print("Could not save the new token; recover the previous cache from the private .bak file.")
return
end
print("Refreshed the contacts token cache.")