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

Outlook Calendar: Refresh a Delegated Access Token

See more Outlook Calendar Examples

Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.

Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.

The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each 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 calendar data private.

Microsoft documentation

Chilkat Lua Downloads

Lua
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/outlookCalendar.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/outlookCalendar.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/outlookCalendar.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 calendar token cache.")