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

Amazon Cognito: Obtain a Machine-to-Machine Access Token

See more Amazon Cognito Examples

Create a dedicated confidential app client with a secret, client_credentials as its only OAuth flow, and allowed custom scopes from a configured resource server. Configure its client_id/domain in a separate app.json profile and put client_secret plus a space-separated custom scope string (for example api.example.com/read) in private m2m-client.json. Sends client_secret_basic authentication and a form-encoded token request. Keep this secret in a controlled backend or backoffice environment, not a public app.

This obtains authorization to your resource-server API, not IAM access to Cognito administration. It does not sign in a person, and Cognito returns no ID token or refresh token. Request another access token when needed, reuse it until near expiry, and check the granted scopes before calling your API. M2M authorization has its own Cognito pricing; do not request a fresh token for every API call.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1 | AWS documentation 2

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- App settings are trusted configuration. Keep a separate account_key/cache per local user.
local app = chilkat.JsonObject.new()
app.strict = true
success = app:load_file("qa_data/cognito/app.json")
if not success then
    print("Could not load Cognito app settings.")
    return
end

if (app:json_type_of("region") ~= 1) or (app:string_of("region") == "") then
    print("Missing or invalid region.")
    return
end

if (app:json_type_of("user_pool_id") ~= 1) or (app:string_of("user_pool_id") == "") then
    print("Missing or invalid user_pool_id.")
    return
end

if (app:json_type_of("client_id") ~= 1) or (app:string_of("client_id") == "") then
    print("Missing or invalid client_id.")
    return
end

if (app:json_type_of("account_key") ~= 1) or (app:string_of("account_key") == "") then
    print("Missing or invalid account_key.")
    return
end

local clientId = app:string_of("client_id")
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://cognito-idp.")
endpoint:append(app:string_of("region"))
endpoint:append(".amazonaws.com/")
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 60
local resp = chilkat.HttpResponse.new()
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
if (app:json_type_of("domain") ~= 1) or (app:string_of("domain") == "") then
    print("Missing or invalid domain.")
    return
end

-- This URL comes from trusted configuration, never from a token or user-supplied URL.
local tokenEndpoint = chilkat.StringBuilder.new()
tokenEndpoint:append(app:string_of("domain"))
tokenEndpoint:append("/oauth2/token")
local secret = chilkat.JsonObject.new()
secret.strict = true
success = secret:load_file("qa_data/cognito/m2m-client.json")
if not success then
    print("Could not load qa_data/cognito/m2m-client.json.")
    return
end

if (secret:json_type_of("client_secret") ~= 1) or (secret:string_of("client_secret") == "") then
    print("Missing or invalid client_secret.")
    return
end

if (secret:json_type_of("scope") ~= 1) or (secret:string_of("scope") == "") then
    print("Missing or invalid scope.")
    return
end

-- Use a dedicated confidential M2M app client, not the public client from the user examples.
http.login = clientId
http.password = secret:string_of("client_secret")
http.basic_auth = true
local req = chilkat.HttpRequest.new()
req.http_verb = "POST"
req.content_type = "application/x-www-form-urlencoded"
req:add_param("grant_type", "client_credentials")
req:add_param("scope", secret:string_of("scope"))
success = http:http_req(tokenEndpoint:get_as_string(), req, resp)
if resp.status_code ~= 200 then
    print("HTTP status: " .. resp.status_code)
    success = result:load(resp.body_str)
    if success then
        print("Error type: " .. result:string_of("__type"))
        print("OAuth error: " .. result:string_of("error"))
    end

    -- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    return
end

if not success then
    print("The HTTP exchange did not complete.")
    return
end

success = result:load(resp.body_str)
if not success then
    print("Expected a JSON response.")
    return
end

if (result:json_type_of("access_token") ~= 1) or (result:string_of("access_token") == "") then
    print("Missing or invalid access_token.")
    return
end

if (result:json_type_of("expires_in") ~= 2) or (result:int_of("expires_in") <= 0) then
    print("Expected a positive token lifetime.")
    return
end

if result:string_of("token_type") ~= "Bearer" then
    print("Expected a Bearer token.")
    return
end

-- Store separately from user tokens: there is no user ID token or refresh token.
result:update_string("client_id", app:string_of("client_id"))
result:update_string("user_pool_id", app:string_of("user_pool_id"))
result:update_string("account_key", app:string_of("account_key"))
local obtained = chilkat.DateTime.new()
success = obtained:set_from_current_system_time()
if not success then
    print("Could not get the acquisition time.")
    return
end

result:update_string("obtained_at", obtained:get_as_timestamp(false))
local resultM2Mtoken = chilkat.FileAccess.new()
success = resultM2Mtoken:dir_ensure_exists("qa_data/tokens")
if not success then
    print("Could not create the private cache directory.")
    return
end

if resultM2Mtoken:file_exists("qa_data/tokens/cognito-m2m.json") then
    success = resultM2Mtoken:file_copy("qa_data/tokens/cognito-m2m.json", "qa_data/tokens/cognito-m2m.json.bak", false)
    if not success then
        print("Could not back up the existing cache.")
        return
    end
end

success = result:write_file("qa_data/tokens/cognito-m2m.json")
if not success then
    print("Could not save M2M token; preserve any previous backup.")
    return
end

print("Machine access token saved privately.")