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

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkDateTime.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkFileAccess.pb"
IncludeFile "CkHttpRequest.pb"
IncludeFile "CkHttpResponse.pb"
IncludeFile "CkStringBuilder.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = 0
    ;  App settings are trusted configuration. Keep a separate account_key/cache per local user.
    app.i = CkJsonObject::ckCreate()
    If app.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(app, 1)
    success = CkJsonObject::ckLoadFile(app,"qa_data/cognito/app.json")
    If success <> 1
        Debug "Could not load Cognito app settings."
        CkJsonObject::ckDispose(app)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(app,"region") <> 1) OR (CkJsonObject::ckStringOf(app,"region") = "")
        Debug "Missing or invalid region."
        CkJsonObject::ckDispose(app)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(app,"user_pool_id") <> 1) OR (CkJsonObject::ckStringOf(app,"user_pool_id") = "")
        Debug "Missing or invalid user_pool_id."
        CkJsonObject::ckDispose(app)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(app,"client_id") <> 1) OR (CkJsonObject::ckStringOf(app,"client_id") = "")
        Debug "Missing or invalid client_id."
        CkJsonObject::ckDispose(app)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(app,"account_key") <> 1) OR (CkJsonObject::ckStringOf(app,"account_key") = "")
        Debug "Missing or invalid account_key."
        CkJsonObject::ckDispose(app)
        ProcedureReturn
    EndIf

    clientId.s = CkJsonObject::ckStringOf(app,"client_id")
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(endpoint,"https://cognito-idp.")
    CkStringBuilder::ckAppend(endpoint,CkJsonObject::ckStringOf(app,"region"))
    CkStringBuilder::ckAppend(endpoint,".amazonaws.com/")
    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHttp::setCkRequireSslCertVerify(http, 1)
    CkHttp::setCkFollowRedirects(http, 0)
    CkHttp::setCkConnectTimeout(http, 20)
    CkHttp::setCkReadTimeout(http, 60)
    resp.i = CkHttpResponse::ckCreate()
    If resp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    body.i = CkJsonObject::ckCreate()
    If body.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    result.i = CkJsonObject::ckCreate()
    If result.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(result, 1)
    If (CkJsonObject::ckJsonTypeOf(app,"domain") <> 1) OR (CkJsonObject::ckStringOf(app,"domain") = "")
        Debug "Missing or invalid domain."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        ProcedureReturn
    EndIf

    ;  This URL comes from trusted configuration, never from a token or user-supplied URL.
    tokenEndpoint.i = CkStringBuilder::ckCreate()
    If tokenEndpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(tokenEndpoint,CkJsonObject::ckStringOf(app,"domain"))
    CkStringBuilder::ckAppend(tokenEndpoint,"/oauth2/token")
    secret.i = CkJsonObject::ckCreate()
    If secret.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(secret, 1)
    success = CkJsonObject::ckLoadFile(secret,"qa_data/cognito/m2m-client.json")
    If success <> 1
        Debug "Could not load qa_data/cognito/m2m-client.json."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(secret,"client_secret") <> 1) OR (CkJsonObject::ckStringOf(secret,"client_secret") = "")
        Debug "Missing or invalid client_secret."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(secret,"scope") <> 1) OR (CkJsonObject::ckStringOf(secret,"scope") = "")
        Debug "Missing or invalid scope."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        ProcedureReturn
    EndIf

    ;  Use a dedicated confidential M2M app client, not the public client from the user examples.
    CkHttp::setCkLogin(http, clientId)
    CkHttp::setCkPassword(http, CkJsonObject::ckStringOf(secret,"client_secret"))
    CkHttp::setCkBasicAuth(http, 1)
    req.i = CkHttpRequest::ckCreate()
    If req.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHttpRequest::setCkHttpVerb(req, "POST")
    CkHttpRequest::setCkContentType(req, "application/x-www-form-urlencoded")
    CkHttpRequest::ckAddParam(req,"grant_type","client_credentials")
    CkHttpRequest::ckAddParam(req,"scope",CkJsonObject::ckStringOf(secret,"scope"))
    success = CkHttp::ckHttpReq(http,CkStringBuilder::ckGetAsString(tokenEndpoint),req,resp)
    If CkHttpResponse::ckStatusCode(resp) <> 200
        Debug "HTTP status: " + Str(CkHttpResponse::ckStatusCode(resp))
        success = CkJsonObject::ckLoad(result,CkHttpResponse::ckBodyStr(resp))
        If success = 1
            Debug "Error type: " + CkJsonObject::ckStringOf(result,"__type")
            Debug "OAuth error: " + CkJsonObject::ckStringOf(result,"error")
        EndIf

        ;  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    If success <> 1
        Debug "The HTTP exchange did not complete."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(result,CkHttpResponse::ckBodyStr(resp))
    If success <> 1
        Debug "Expected a JSON response."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(result,"access_token") <> 1) OR (CkJsonObject::ckStringOf(result,"access_token") = "")
        Debug "Missing or invalid access_token."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(result,"expires_in") <> 2) OR (CkJsonObject::ckIntOf(result,"expires_in") <= 0)
        Debug "Expected a positive token lifetime."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    If CkJsonObject::ckStringOf(result,"token_type") <> "Bearer"
        Debug "Expected a Bearer token."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        ProcedureReturn
    EndIf

    ;  Store separately from user tokens: there is no user ID token or refresh token.
    CkJsonObject::ckUpdateString(result,"client_id",CkJsonObject::ckStringOf(app,"client_id"))
    CkJsonObject::ckUpdateString(result,"user_pool_id",CkJsonObject::ckStringOf(app,"user_pool_id"))
    CkJsonObject::ckUpdateString(result,"account_key",CkJsonObject::ckStringOf(app,"account_key"))
    obtained.i = CkDateTime::ckCreate()
    If obtained.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkDateTime::ckSetFromCurrentSystemTime(obtained)
    If success <> 1
        Debug "Could not get the acquisition time."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        CkDateTime::ckDispose(obtained)
        ProcedureReturn
    EndIf

    CkJsonObject::ckUpdateString(result,"obtained_at",CkDateTime::ckGetAsTimestamp(obtained,0))
    resultM2Mtoken.i = CkFileAccess::ckCreate()
    If resultM2Mtoken.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkFileAccess::ckDirEnsureExists(resultM2Mtoken,"qa_data/tokens")
    If success <> 1
        Debug "Could not create the private cache directory."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        CkDateTime::ckDispose(obtained)
        CkFileAccess::ckDispose(resultM2Mtoken)
        ProcedureReturn
    EndIf

    If CkFileAccess::ckFileExists(resultM2Mtoken,"qa_data/tokens/cognito-m2m.json") = 1
        success = CkFileAccess::ckFileCopy(resultM2Mtoken,"qa_data/tokens/cognito-m2m.json","qa_data/tokens/cognito-m2m.json.bak",0)
        If success <> 1
            Debug "Could not back up the existing cache."
            CkJsonObject::ckDispose(app)
            CkStringBuilder::ckDispose(endpoint)
            CkHttp::ckDispose(http)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(body)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkJsonObject::ckDispose(secret)
            CkHttpRequest::ckDispose(req)
            CkDateTime::ckDispose(obtained)
            CkFileAccess::ckDispose(resultM2Mtoken)
            ProcedureReturn
        EndIf

    EndIf

    success = CkJsonObject::ckWriteFile(result,"qa_data/tokens/cognito-m2m.json")
    If success <> 1
        Debug "Could not save M2M token; preserve any previous backup."
        CkJsonObject::ckDispose(app)
        CkStringBuilder::ckDispose(endpoint)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(body)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkJsonObject::ckDispose(secret)
        CkHttpRequest::ckDispose(req)
        CkDateTime::ckDispose(obtained)
        CkFileAccess::ckDispose(resultM2Mtoken)
        ProcedureReturn
    EndIf

    Debug "Machine access token saved privately."


    CkJsonObject::ckDispose(app)
    CkStringBuilder::ckDispose(endpoint)
    CkHttp::ckDispose(http)
    CkHttpResponse::ckDispose(resp)
    CkJsonObject::ckDispose(body)
    CkJsonObject::ckDispose(result)
    CkStringBuilder::ckDispose(tokenEndpoint)
    CkJsonObject::ckDispose(secret)
    CkHttpRequest::ckDispose(req)
    CkDateTime::ckDispose(obtained)
    CkFileAccess::ckDispose(resultM2Mtoken)


    ProcedureReturn
EndProcedure