Sample code for 30+ languages & platforms
AutoIt 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 AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  App settings are trusted configuration. Keep a separate account_key/cache per local user.
$oApp = ObjCreate("Chilkat.JsonObject")
$oApp.Strict = True
$bSuccess = $oApp.LoadFile("qa_data/cognito/app.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load Cognito app settings." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("region") <> 1) Or ($oApp.StringOf("region") = "")) Then
    ConsoleWrite("Missing or invalid region." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("user_pool_id") <> 1) Or ($oApp.StringOf("user_pool_id") = "")) Then
    ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("client_id") <> 1) Or ($oApp.StringOf("client_id") = "")) Then
    ConsoleWrite("Missing or invalid client_id." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("account_key") <> 1) Or ($oApp.StringOf("account_key") = "")) Then
    ConsoleWrite("Missing or invalid account_key." & @CRLF)
    Exit
EndIf

Local $sClientId = $oApp.StringOf("client_id")
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://cognito-idp.")
$oEndpoint.Append($oApp.StringOf("region"))
$oEndpoint.Append(".amazonaws.com/")
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 60
$oResp = ObjCreate("Chilkat.HttpResponse")
$oBody = ObjCreate("Chilkat.JsonObject")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
If (($oApp.JsonTypeOf("domain") <> 1) Or ($oApp.StringOf("domain") = "")) Then
    ConsoleWrite("Missing or invalid domain." & @CRLF)
    Exit
EndIf

;  This URL comes from trusted configuration, never from a token or user-supplied URL.
$oTokenEndpoint = ObjCreate("Chilkat.StringBuilder")
$oTokenEndpoint.Append($oApp.StringOf("domain"))
$oTokenEndpoint.Append("/oauth2/token")
$oSecret = ObjCreate("Chilkat.JsonObject")
$oSecret.Strict = True
$bSuccess = $oSecret.LoadFile("qa_data/cognito/m2m-client.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load qa_data/cognito/m2m-client.json." & @CRLF)
    Exit
EndIf

If (($oSecret.JsonTypeOf("client_secret") <> 1) Or ($oSecret.StringOf("client_secret") = "")) Then
    ConsoleWrite("Missing or invalid client_secret." & @CRLF)
    Exit
EndIf

If (($oSecret.JsonTypeOf("scope") <> 1) Or ($oSecret.StringOf("scope") = "")) Then
    ConsoleWrite("Missing or invalid scope." & @CRLF)
    Exit
EndIf

;  Use a dedicated confidential M2M app client, not the public client from the user examples.
$oHttp.Login = $sClientId
$oHttp.Password = $oSecret.StringOf("client_secret")
$oHttp.BasicAuth = True
$oReq = ObjCreate("Chilkat.HttpRequest")
$oReq.HttpVerb = "POST"
$oReq.ContentType = "application/x-www-form-urlencoded"
$oReq.AddParam "grant_type","client_credentials"
$oReq.AddParam "scope",$oSecret.StringOf("scope")
$bSuccess = $oHttp.HttpReq($oTokenEndpoint.GetAsString(),$oReq,$oResp)
If ($oResp.StatusCode <> 200) Then
    ConsoleWrite("HTTP status: " & $oResp.StatusCode & @CRLF)
    $bSuccess = $oResult.Load($oResp.BodyStr)
    If ($bSuccess = True) Then
        ConsoleWrite("Error type: " & $oResult.StringOf("__type") & @CRLF)
        ConsoleWrite("OAuth error: " & $oResult.StringOf("error") & @CRLF)
    EndIf

    ;  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("The HTTP exchange did not complete." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a JSON response." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("access_token") <> 1) Or ($oResult.StringOf("access_token") = "")) Then
    ConsoleWrite("Missing or invalid access_token." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("expires_in") <> 2) Or ($oResult.IntOf("expires_in") <= 0)) Then
    ConsoleWrite("Expected a positive token lifetime." & @CRLF)
    Exit
EndIf

If ($oResult.StringOf("token_type") <> "Bearer") Then
    ConsoleWrite("Expected a Bearer token." & @CRLF)
    Exit
EndIf

;  Store separately from user tokens: there is no user ID token or refresh token.
$oResult.UpdateString("client_id",$oApp.StringOf("client_id"))
$oResult.UpdateString("user_pool_id",$oApp.StringOf("user_pool_id"))
$oResult.UpdateString("account_key",$oApp.StringOf("account_key"))
$oObtained = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oObtained.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not get the acquisition time." & @CRLF)
    Exit
EndIf

$oResult.UpdateString("obtained_at",$oObtained.GetAsTimestamp(False))
$oResultM2Mtoken = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oResultM2Mtoken.DirEnsureExists("qa_data/tokens")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the private cache directory." & @CRLF)
    Exit
EndIf

If ($oResultM2Mtoken.FileExists("qa_data/tokens/cognito-m2m.json") = True) Then
    $bSuccess = $oResultM2Mtoken.FileCopy("qa_data/tokens/cognito-m2m.json","qa_data/tokens/cognito-m2m.json.bak",False)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not back up the existing cache." & @CRLF)
        Exit
    EndIf

EndIf

$bSuccess = $oResult.WriteFile("qa_data/tokens/cognito-m2m.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save M2M token; preserve any previous backup." & @CRLF)
    Exit
EndIf

ConsoleWrite("Machine access token saved privately." & @CRLF)