Sample code for 30+ languages & platforms
Lua

Refresh Access Token on 401 Unauthorized and Retry (Service Account)

See more Google Cloud Storage Examples

Demonstrates how to handle an expired access token error, refresh the token, and retry the request. (In this case, the request is to download an object from Google Cloud Storage.)

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- This example uses a previously obtained access token having permission for the
-- scope "https://www.googleapis.com/auth/cloud-platform"

-- In this example, Get Google Cloud Storage OAuth2 Access Token,
-- the service account access token was saved to a text file.  This example fetches the access token from the file..
local sbToken = chilkat.StringBuilder.new()
local success = sbToken:load_file("qa_data/tokens/googleCloudStorageAccessToken.txt", "utf-8")
if not success then
    print("Failed to load access token.")
    return
end

local http = chilkat.Http.new()

http.auth_token = sbToken:get_as_string()

-- Construct a URL to download an object named "starfish.jpg" from the "chilkat-ocean" bucket.
http:set_url_var("bucket_name", "chilkat-ocean")
http:set_url_var("object_name", "starfish.jpg")
local url = "https://www.googleapis.com/storage/v1/b/{$bucket_name}/o/{$object_name}?alt=media"

-- If there is an error response, then we didn't actually download the file data,
-- but instead we downloaded an error response..
local fileData = chilkat.BinData.new()
success = http:download_bd(url, fileData)
local responseCode = http.last_status
if (not success) and (responseCode ~= 401) then
    print(http.last_error_text)
    return
end

if responseCode == 401 then
    print("Received 401 Unauthorized response. Attempting to refresh the access token...")

    -- May be that the access token expired.
    -- Load our JSON key and request a new access token, then retry the original request.
    local fac = chilkat.FileAccess.new()
    local jsonKey = fac:read_entire_text_file("qa_data/googleApi/ChilkatCloud-13a07a2e8b3f.json", "utf-8")
    if not fac.last_method_success then
        print(fac.last_error_text)
        return
    end

    local gAuth = chilkat.AuthGoogle.new()
    gAuth.json_key = jsonKey
    gAuth.scope = "https://www.googleapis.com/auth/cloud-platform"
    gAuth.expire_num_seconds = 3600
    gAuth.sub_email_address = ""

    local tlsSock = chilkat.Socket.new()
    success = tlsSock:connect("www.googleapis.com", 443, true, 5000)
    if not success then
        print(tlsSock.last_error_text)
        return
    end

    success = gAuth:obtain_access_token(tlsSock)
    if not success then
        print(gAuth.last_error_text)
        return
    end

    fac:write_entire_text_file("qa_data/tokens/googleCloudStorageAccessToken.txt", gAuth.access_token, "utf-8", false)

    -- Retry the original request.
    http.auth_token = gAuth.access_token
    success = http:download_bd(url, fileData)
    if not success then
        print(http.last_error_text)
        return
    end
end

if responseCode ~= 200 then
    -- Get the error response
    local sbErrorResponse = chilkat.StringBuilder.new()
    sbErrorResponse:append_bd(fileData, "utf-8", 0, 0)
    print("Error response code = " .. responseCode)
    print("Error:")
    print(sbErrorResponse:get_as_string())
    return
end

print("Success.")

-- Save the downloaded data to a file.
success = fileData:write_file("qa_output/starfish.jpg")