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 Tcl Downloads
load ./chilkat.dll
set success 0
# Assumes Chilkat is unlocked. See Global Unlock Sample.
set success 0
# App settings are trusted configuration. Keep a separate account_key/cache per local user.
set app [new_CkJsonObject]
CkJsonObject_put_Strict $app 1
set success [CkJsonObject_LoadFile $app "qa_data/cognito/app.json"]
if {$success != 1} then {
puts "Could not load Cognito app settings."
delete_CkJsonObject $app
exit
}
if {expr [[CkJsonObject_JsonTypeOf $app "region"] != 1] || [[CkJsonObject_stringOf $app "region"] == ""]} then {
puts "Missing or invalid region."
delete_CkJsonObject $app
exit
}
if {expr [[CkJsonObject_JsonTypeOf $app "user_pool_id"] != 1] || [[CkJsonObject_stringOf $app "user_pool_id"] == ""]} then {
puts "Missing or invalid user_pool_id."
delete_CkJsonObject $app
exit
}
if {expr [[CkJsonObject_JsonTypeOf $app "client_id"] != 1] || [[CkJsonObject_stringOf $app "client_id"] == ""]} then {
puts "Missing or invalid client_id."
delete_CkJsonObject $app
exit
}
if {expr [[CkJsonObject_JsonTypeOf $app "account_key"] != 1] || [[CkJsonObject_stringOf $app "account_key"] == ""]} then {
puts "Missing or invalid account_key."
delete_CkJsonObject $app
exit
}
set clientId [CkJsonObject_stringOf $app "client_id"]
set endpoint [new_CkStringBuilder]
CkStringBuilder_Append $endpoint "https://cognito-idp."
CkStringBuilder_Append $endpoint [CkJsonObject_stringOf $app "region"]
CkStringBuilder_Append $endpoint ".amazonaws.com/"
set http [new_CkHttp]
CkHttp_put_RequireSslCertVerify $http 1
CkHttp_put_FollowRedirects $http 0
CkHttp_put_ConnectTimeout $http 20
CkHttp_put_ReadTimeout $http 60
set resp [new_CkHttpResponse]
set body [new_CkJsonObject]
set result [new_CkJsonObject]
CkJsonObject_put_Strict $result 1
if {expr [[CkJsonObject_JsonTypeOf $app "domain"] != 1] || [[CkJsonObject_stringOf $app "domain"] == ""]} then {
puts "Missing or invalid domain."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
exit
}
# This URL comes from trusted configuration, never from a token or user-supplied URL.
set tokenEndpoint [new_CkStringBuilder]
CkStringBuilder_Append $tokenEndpoint [CkJsonObject_stringOf $app "domain"]
CkStringBuilder_Append $tokenEndpoint "/oauth2/token"
set secret [new_CkJsonObject]
CkJsonObject_put_Strict $secret 1
set success [CkJsonObject_LoadFile $secret "qa_data/cognito/m2m-client.json"]
if {$success != 1} then {
puts "Could not load qa_data/cognito/m2m-client.json."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
exit
}
if {expr [[CkJsonObject_JsonTypeOf $secret "client_secret"] != 1] || [[CkJsonObject_stringOf $secret "client_secret"] == ""]} then {
puts "Missing or invalid client_secret."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
exit
}
if {expr [[CkJsonObject_JsonTypeOf $secret "scope"] != 1] || [[CkJsonObject_stringOf $secret "scope"] == ""]} then {
puts "Missing or invalid scope."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
exit
}
# Use a dedicated confidential M2M app client, not the public client from the user examples.
CkHttp_put_Login $http $clientId
CkHttp_put_Password $http [CkJsonObject_stringOf $secret "client_secret"]
CkHttp_put_BasicAuth $http 1
set req [new_CkHttpRequest]
CkHttpRequest_put_HttpVerb $req "POST"
CkHttpRequest_put_ContentType $req "application/x-www-form-urlencoded"
CkHttpRequest_AddParam $req "grant_type" "client_credentials"
CkHttpRequest_AddParam $req "scope" [CkJsonObject_stringOf $secret "scope"]
set success [CkHttp_HttpReq $http [CkStringBuilder_getAsString $tokenEndpoint] $req $resp]
if {[CkHttpResponse_get_StatusCode $resp] != 200} then {
puts "HTTP status: [CkHttpResponse_get_StatusCode $resp]"
set success [CkJsonObject_Load $result [CkHttpResponse_bodyStr $resp]]
if {$success == 1} then {
puts "Error type: [CkJsonObject_stringOf $result __type]"
puts "OAuth error: [CkJsonObject_stringOf $result error]"
}
# Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
if {$success != 1} then {
puts "The HTTP exchange did not complete."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
set success [CkJsonObject_Load $result [CkHttpResponse_bodyStr $resp]]
if {$success != 1} then {
puts "Expected a JSON response."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
if {expr [[CkJsonObject_JsonTypeOf $result "access_token"] != 1] || [[CkJsonObject_stringOf $result "access_token"] == ""]} then {
puts "Missing or invalid access_token."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
if {expr [[CkJsonObject_JsonTypeOf $result "expires_in"] != 2] || [[CkJsonObject_IntOf $result "expires_in"] <= 0]} then {
puts "Expected a positive token lifetime."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
if {[CkJsonObject_stringOf $result "token_type"] != "Bearer"} then {
puts "Expected a Bearer token."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
exit
}
# Store separately from user tokens: there is no user ID token or refresh token.
CkJsonObject_UpdateString $result "client_id" [CkJsonObject_stringOf $app "client_id"]
CkJsonObject_UpdateString $result "user_pool_id" [CkJsonObject_stringOf $app "user_pool_id"]
CkJsonObject_UpdateString $result "account_key" [CkJsonObject_stringOf $app "account_key"]
set obtained [new_CkDateTime]
set success [CkDateTime_SetFromCurrentSystemTime $obtained]
if {$success != 1} then {
puts "Could not get the acquisition time."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
delete_CkDateTime $obtained
exit
}
CkJsonObject_UpdateString $result "obtained_at" [CkDateTime_getAsTimestamp $obtained 0]
set resultM2Mtoken [new_CkFileAccess]
set success [CkFileAccess_DirEnsureExists $resultM2Mtoken "qa_data/tokens"]
if {$success != 1} then {
puts "Could not create the private cache directory."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
delete_CkDateTime $obtained
delete_CkFileAccess $resultM2Mtoken
exit
}
if {[CkFileAccess_FileExists $resultM2Mtoken "qa_data/tokens/cognito-m2m.json"] == 1} then {
set success [CkFileAccess_FileCopy $resultM2Mtoken "qa_data/tokens/cognito-m2m.json" "qa_data/tokens/cognito-m2m.json.bak" 0]
if {$success != 1} then {
puts "Could not back up the existing cache."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
delete_CkDateTime $obtained
delete_CkFileAccess $resultM2Mtoken
exit
}
}
set success [CkJsonObject_WriteFile $result "qa_data/tokens/cognito-m2m.json"]
if {$success != 1} then {
puts "Could not save M2M token; preserve any previous backup."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
delete_CkDateTime $obtained
delete_CkFileAccess $resultM2Mtoken
exit
}
puts "Machine access token saved privately."
delete_CkJsonObject $app
delete_CkStringBuilder $endpoint
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $body
delete_CkJsonObject $result
delete_CkStringBuilder $tokenEndpoint
delete_CkJsonObject $secret
delete_CkHttpRequest $req
delete_CkDateTime $obtained
delete_CkFileAccess $resultM2Mtoken