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

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics 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/oneDrive.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/oneDrive.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/oneDrive.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 OneDrive token cache.")